【问题标题】:Cannot close multithreaded Tkinter app on X button无法在 X 按钮上关闭多线程 Tkinter 应用程序
【发布时间】:2014-05-19 13:45:07
【问题描述】:

我的应用具有以下结构:

import tkinter as tk
from threading import Thread

class MyWindow(tk.Frame):
    ...  # constructor, methods etc.

def main():
    window = MyWindow()
    Thread(target=window.mainloop).start()
    ...  # repeatedly draw stuff on the window, no event handling, no interaction

main()

应用程序运行完美,但如果我按下 X(关闭)按钮,它会关闭窗口,但不会停止进程,有时甚至会抛出 TclError

编写这样的应用程序的正确方法是什么?如何以线程安全的方式或没有线程的方式编写它?

【问题讨论】:

    标签: python multithreading tkinter python-multithreading


    【解决方案1】:

    主事件循环应该在主线程中,绘图线程应该在第二线程中。

    这个应用的正确写法是这样的:

    import tkinter as tk
    from threading import Thread
    
    class DrawingThread(Thread):
        def __init__(wnd):
            self.wnd = wnd
            self.is_quit = False
    
        def run():
            while not self.is_quit:
                ... # drawing sth on window
    
        def stop():
            # to let this thread quit.
            self.is_quit = True
    
    class MyWindow(tk.Frame):
        ...  # constructor, methods etc.
        self.thread = DrawingThread(self)
        self.thread.start()
    
        on_close(self, event):
            # stop the drawing thread.
            self.thread.stop()
    
    def main():
        window = MyWindow()
        window.mainloop()
    
    main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-21
      • 2021-12-15
      相关资源
      最近更新 更多