简体   繁体   English

Tkinter 标签小部件中的动画文本(python)

[英]Animate Text in Tkinter Label Widget (python)

i want to animate a label text in tkinter (python).我想在 tkinter (python) 中为标签文本设置动画。 for that purpose, i am using time.sleep() method for updating 1 character in Label widget after a second but it is not updating Label widget instantly rather it is updating label at once at the end of timer.为此,我使用 time.sleep() 方法在一秒钟后更新 Label 小部件中的 1 个字符,但它不会立即更新 Label 小部件,而是在计时器结束时立即更新标签。 How could i fix this?.我该如何解决这个问题? Here is my code:-这是我的代码:-

from tkinter import *
import time


global a



def update(a):
    txt = 'Sample Text'
    mylabel.configure(text=txt[0:a])
    
def timer():
    global a
    a = 0
    lenth = len('Sample Text')
    start = time.time()
    while True:
        # Do other stuff, it won't be blocked
        time.sleep(0.1)

        # When 1 sec or more has elapsed...
        if time.time() - start > 1:
            start = time.time()
            a = a + 1

            # This will be updated once per second
            print("{} counter".format(a))
            update(a)
            # Count up to the lenth of text, ending loop
            if a > lenth:
                break

root = Tk()
root.geometry('300x300')

mylabel = Label(root, text="S", font=('Bell', 36, 'bold'))
mylabel.pack(pady=5)

root.after(3000, timer)
root.mainloop()

It is not recommended to use loop and time.sleep() in the main thread of a tkinter application because it will block the tkinter mainloop() from updating widgets until the loop exits.不建议在 tkinter 应用程序的主线程中使用 loop 和 time.sleep( time.sleep() ,因为它会阻止mainloop()更新小部件,直到循环退出。 That is why you can only see the result after the loop completes.这就是为什么您只能在循环完成后才能看到结果。

Use .after() instead:使用.after()代替:

import tkinter as tk

root = tk.Tk()
#root.geometry('300x300')

txt = 'Sample Text'

lbl = tk.Label(root, font='Bell 36 bold', width=len(txt))
lbl.pack(pady=5)

def animate_label(text, n=0):
    if n < len(text)-1:
        # not complete yet, schedule next run one second later
        lbl.after(1000, animate_label, text, n+1)
    # update the text of the label
    lbl['text'] = text[:n+1]

# start the "after loop" one second later
root.after(1000, animate_label, txt)
root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM