如何定期调用方法/函数? (time.sleep失败) [英] How to call a method / function periodically? (time.sleep fails)

查看:257
本文介绍了如何定期调用方法/函数? (time.sleep失败)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何定期呼叫update?我尝试了以下操作,但是它跳过了显示limit秒的GUI,然后仅显示了最近的更新:

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

然后我尝试:

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?

推荐答案

而不是time.sleep,请尝试按以下方式使用after,因为它不会延迟您的GUI显示:

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

这篇关于如何定期调用方法/函数? (time.sleep失败)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆