简体   繁体   English

根据带有 tkinter 的计时器显示标签

[英]Display a label depending on a timer with tkinter

I would like to display the value of i, rest for 2 sec, then show the new value of i.我想显示 i 的值,休息 2 秒,然后显示 i 的新值。

But with this code, it just display the very last value of i, not even the original value.但是使用此代码,它只显示 i 的最后一个值,甚至不显示原始值。 Anyone can help me?任何人都可以帮助我吗? Thank you谢谢

from tkinter import *
from time import sleep

root=Tk()
touracc=StringVar()
printer=Label(root, textvariable=touracc,bg="#85c17e")
touracc.set('yo')

for i in range(2):
    touracc.set(str(i))
    sleep(2)


printer.pack()
root.mainloop()

It is because sleep() will block tkinter from updating.这是因为sleep()会阻止 tkinter 更新。 Use after() instead:使用after()代替:

from tkinter import *

root=Tk()

touracc=StringVar()
printer=Label(root, textvariable=touracc,bg="#85c17e")
printer.pack()
touracc.set('yo')

def update(n=0):
    if n < 2:    
        touracc.set(n)
        root.after(2000, update, n+1)

root.after(2000, update)
root.mainloop()

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

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