如何定期调用方法/函数? (time.sleep失败)

时间:2017-12-10 22:27:44

标签: python tkinter periodic-task periodicity

如何定期致电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()

其结果与前者完全相同。那我怎么能这样做呢?

1 个答案:

答案 0 :(得分:1)

而不是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()