Cannot close multithreaded Tkinter app on X button

萝らか妹 提交于 2019-12-31 07:17:13

问题


My app has the following structure:

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

The app runs perfectly, but if I press the X (close) button, it closes the window, but does not stop the process, and sometimes even throws a TclError.

What is the right way to write an app like this? How to write it in a thread-safe way or without threads?


回答1:


Main event loop should in main thread, and the drawing thread should in the second thread.

The right way to write this app is like this:

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


来源:https://stackoverflow.com/questions/23739453/cannot-close-multithreaded-tkinter-app-on-x-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!