使用tkinter根据计时器显示标签



我想显示I的值,休息2秒,然后显示I的新值。

但使用此代码,它只显示i的最后一个值,甚至不是原始值。有人能帮我吗?谢谢

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()

这是因为sleep()会阻止tkinter更新。改为使用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()

最新更新