2014-05-19 117 views
0

我的应用程序的结构如下:无法在X按钮关闭多线程的Tkinter应用

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

主事件循环应该在主线程中,并且绘制线程应该在第二个线程中。

写这个程序,正确的做法是这样的:

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