2014-05-19 118 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()