How to call a method / function periodically? (time.sleep fails) [duplicate]

一曲冷凌霜 提交于 2019-12-02 19:53:13

问题


How can I call update periodically? I tried the following but it skips showing GUI for the limit seconds and then shows only the last update:

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

Then I tried:

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

Which resulted the exact same way as the former. So how can I do this?


回答1:


Instead of time.sleep try using after in the following way as it won't delay your GUI to show:

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


来源:https://stackoverflow.com/questions/47744143/how-to-call-a-method-function-periodically-time-sleep-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!