了解运行后台线程时Tkinter窗口的响应

2024-04-29 00:40:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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("<<update_gui>>", 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

程序被冻结了。我做错什么了吗?在


Tags: theselfinittkinterdefguiroot线程
1条回答
网友
1楼 · 发布于 2024-04-29 00:40:53

正如我在a comment中建议的,如果在后台线程中生成事件后调用root.update(),它将强制应用程序自身更新。这是fixed the original issue,但我不能遍历具体的执行流程,因为示例代码不足以测试。在

相关问题 更多 >