如何定期调用方法/函数? (time.sleep 失败)
How to call a method / function periodically? (time.sleep fails)
如何定期调用 update
?我尝试了以下操作,但它在 limit
秒内跳过显示 GUI,然后仅显示最后更新:
import tkinter as tk
import time
root = tk.Tk()
widget = tk.Label(root, text="Initial text")
widget.pack()
def update():
global widget
limit = 3
period = 1
for each in range(limit):
widget['text'] = each
time.sleep(period)
update()
root.mainloop()
然后我尝试了:
import tkinter as tk
import time
root = tk.Tk()
widget = tk.Label(root, text="Initial text")
widget.pack()
def update():
global widget, period
widget['text'] = each
time.sleep(period)
limit = 3
period = 1
for each in range(limit):
update()
root.mainloop()
结果与前者完全相同。那我该怎么做呢?
而不是 time.sleep
尝试按以下方式使用 after
因为它不会延迟您的 GUI 显示:
import tkinter as tk
def update():
global each, limit, period, widget
if each < limit:
widget['text'] = each
each += 1
widget.after(period*1000, update)
root = tk.Tk()
widget = tk.Label(root, text="Initial text")
widget.pack()
limit = 3
period = 1
each = 0
update()
root.mainloop()
如何定期调用 update
?我尝试了以下操作,但它在 limit
秒内跳过显示 GUI,然后仅显示最后更新:
import tkinter as tk
import time
root = tk.Tk()
widget = tk.Label(root, text="Initial text")
widget.pack()
def update():
global widget
limit = 3
period = 1
for each in range(limit):
widget['text'] = each
time.sleep(period)
update()
root.mainloop()
然后我尝试了:
import tkinter as tk
import time
root = tk.Tk()
widget = tk.Label(root, text="Initial text")
widget.pack()
def update():
global widget, period
widget['text'] = each
time.sleep(period)
limit = 3
period = 1
for each in range(limit):
update()
root.mainloop()
结果与前者完全相同。那我该怎么做呢?
而不是 time.sleep
尝试按以下方式使用 after
因为它不会延迟您的 GUI 显示:
import tkinter as tk
def update():
global each, limit, period, widget
if each < limit:
widget['text'] = each
each += 1
widget.after(period*1000, update)
root = tk.Tk()
widget = tk.Label(root, text="Initial text")
widget.pack()
limit = 3
period = 1
each = 0
update()
root.mainloop()