无法通过X按钮关闭多线程Tkinter应用

1 投票
1 回答
1050 浏览
提问于 2025-04-18 06:59

我的应用程序结构如下:

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 错误。

那么,写一个这样的应用程序的正确方法是什么呢?怎么才能写得安全一些,或者不使用线程呢?

1 个回答

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

撰写回答