Python 无法关闭X按钮上的多线程Tkinter应用程序

Python 无法关闭X按钮上的多线程Tkinter应用程序,python,multithreading,tkinter,python-multithreading,Python,Multithreading,Tkinter,Python Multithreading,我的应用程序具有以下结构: 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 wi

我的应用程序具有以下结构:

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


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

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

编写此应用程序的正确方法如下:

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()