我正在使用Tkinter创建一个GUI,它从一个计算线程不断更新。为了保持GUI的响应性,我在这个线程的每个循环中创建一个事件,告诉主线程(在其中创建了Tkinter窗口)用计算的数据更新GUI。线程的结构如下所示:class background_thread(threading.Thread):
def __init__(self, parent, stopper):
threading.Thread.__init__(self)
self.parent = parent
self.stopper = stopper
### Init. variables ###
def run(self):
while(not self.stopper.is_set()):
### Compute data ###
root.event_generate("<>", when = "now")
这很好地工作,但是当线程运行时,我很难理解Tkinter窗口的行为。首先,即使我的mainloop()仍然有响应(我每秒大约得到40帧),窗口本身根本没有响应。我的意思是说,它不可能被拖动或关闭。造成这种情况的原因是什么?有什么办法可以防止它?在
由此产生的一个问题是,我必须在关闭窗口之前停止线程。为此,我使用一个按钮来切换其执行:
^{pr2}$
但如果我试图重新定义窗口关闭按钮协议:root.protocol("WM_DELETE_WINDOW", on_closing)
def on_closing():
if(self.background_thread.isAlive()):
self.stopper.set() # Asks the thread to stop
self.background_thread.join() # Waits for the thread to stop
root.destroy() # Closes the window
程序被冻结了。我做错什么了吗?在