【发布时间】:2022-02-15 17:47:14
【问题描述】:
我创建了一个示例代码,因为我的原件太大并且其中包含私人信息(我自己的)。
从 Tkinter GUI 运行程序时,它会运行该程序,但由于 time.sleep() 阻止 GUI 更新,因此导致 GUI 无响应。
我试图避免使用计时器,因为它会在一段时间后触发不同的函数,而不是简单地暂停函数然后继续执行相同的函数。
是否有不阻塞 GUI 但仍会在函数内部添加延迟的替代方法?
示例代码:
from tkinter import *
import time
wn = Tk()
wn.geometry("400x300")
MyLabel = Label(wn, text="This is a Status Bar")
MyLabel.pack()
def MyFunction():
Value = 1
while Value < 10:
print("Do something")
time.sleep(1) **# - here blocks everything outside of the function**
MyLabel.config(text=Value)
# A lot more code is under here so I cannot use a timer that fires a new function
Value = 1
MyButton = Button(wn, text="Run Program", command=MyFunction)
MyButton.pack()
wn.mainloop()
编辑:非常感谢,您的回答快速而有帮助,我更改了代码并在延迟后添加了“wn.mainloop()”,并将“time.sleep(1)”替换为 wn.after(100 , wn.after(10, MyLabel.config(text=Value))
这是最终代码:
from tkinter import *
import time
wn = Tk()
wn.geometry("400x300")
MyLabel = Label(wn, text="This is a Status Bar")
MyLabel.pack()
def MyFunction():
Value = 0
while Value < 10:
print("Do something")
wn.after(10, MyLabel.config(text=Value))
Value += 1
wn.mainloop()
MyButton = Button(wn, text="Run Program", command=MyFunction)
MyButton.pack()
wn.mainloop()
【问题讨论】:
-
为什么需要屏蔽 GUI?
-
无法在函数中执行此操作 - 如果您不返回 Tkinter 的主循环,则 GUI 将被冻结。正确的解决方案是使用
.after()(带有 2 个以上参数的版本)来安排函数以供以后执行 - 是的,这确实需要与您的程序完全不同的结构。 -
另一种方法是使用线程和事件队列模型,您的
MyFunction在单独的线程中运行。还可以选择在单独的线程中使用 async/await(和asyncio.sleep);请参阅stackoverflow.com/questions/49958180/… 获取食谱。 -
wn.after(10, MyLabel.config(text=Value)不会像您认为的那样做。wm.after(10, MyLabel.config(text=Value)立即运行配置步骤。