我有一个简单的 GUI,它从另一个 python 文件运行各种脚本,一切正常,直到 GUI 运行一个包含 while 循环的函数,此时 GUI 似乎崩溃并变得不活动。有谁知道如何克服这个问题,因为我相信这与更新 GUI 有关,谢谢。下面是我的 GUI 的简化版本。
图形用户界面
#!/usr/bin/env python
# Python 3
from tkinter import *
from tkinter import ttk
from Entry import ConstrainedEntry
import tkinter.messagebox
import functions
AlarmCode = "2222"
root = Tk()
root.title("Simple Interface")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
ttk.Button(mainframe, width=12,text="ButtonTest",
command=lambda: functions.test()).grid(
column=5, row=5, sticky=SE)
for child in mainframe.winfo_children():
child.grid_configure(padx=5, pady=5)
root.mainloop()
功能
def test():
period = 0
while True:
if (period) <=100:
time.sleep(1)
period +=1
print(period)
else:
print("100 seconds has passed")
break
上面会发生的是,当循环运行时应用程序将崩溃。如果我在该时间段过后在 else 语句中插入一个中断,一切都会正常工作。我希望用户能够在循环中单击,因为该 GUI 将运行许多不同的功能。
最佳答案
不要在与 Tkinter 代码相同的线程中使用 time.sleep
:它会卡住 GUI,直到 test
执行完成。为了避免这种情况,您应该使用 after
小部件方法:
# GUI
ttk.Button(mainframe, width=12,text="ButtonTest",
command=lambda: functions.test(root))
.grid(column=5, row=5, sticky=SE)
# functions
def test(root, period=0):
if period <= 100:
period += 1
print(period)
root.after(1000, lambda: test(root, period))
else:
print("100 seconds has passed")
更新:
在您的评论中,您还添加了您的代码不会使用 time.sleep
,因此您原来的示例可能不是最合适的。在这种情况下,您可以创建一个新线程来运行您的密集代码。
请注意,我首先发布了 after
的替代方案,因为只有在完全必要的情况下才应使用多线程 - 它会增加应用程序的开销,并增加调试代码的难度。
from threading import Thread
ttk.Button(mainframe, width=12,text="ButtonTest",
command=lambda: Thread(target=functions.test).start())
.grid(column=5, row=5, sticky=SE)
# functions
def test():
for x in range(100):
time.sleep(1) # Simulate intense task (not real code!)
print(x)
print("100 seconds has passed")
关于user-interface - 进入 while 循环时 Tkinter 出现 GUI 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15602660/