Python app with tkinter and threading error at closing

时间:2015-10-31 00:03:40

标签: python multithreading tkinter

I am writing this software for a project homework, but I am having trouble with mixing threads and tkinter. The following piece works mostly as expected, but when I close it (after starting it in the Python shell), windows shows an error: "Python stopped working". import threading import time import tkinter import tkinter.ttk class BTClient: def __init__(self, master): self.root = master self.root.bind("<Destroy>", self.on_destroy) self.t = threading.Thread(target=self.update) self.running = False def on_destroy(self, event): self.running = False def run_thread(self): self.running = True self.t.start() def update(self): while self.running: print("Update.") time.sleep(1) def main(args): root = tkinter.Tk() client = BTClient(root) client.run_thread() root.mainloop() if __name__ == "__main__": import sys main(sys.argv) How can I solve that problem? Is it caused by the design I am using? Should I change it? Edit 1: When I remove the self.root declaration in __init__ and only use the master reference the problem is solved, but I need to have references to the GUI objects, first to build the GUI and also to get input from them, so I don't know how to solve that. Maybe passing objects as arguments to everything that may need them?

2 个答案:

答案 0 :(得分:1)

如果没有看到您的实际代码,很难确切知道发生了什么,但我会将您的线程方法设置为BTClient之外的函数,并将线程移到客户端之外并在之后添加对thread.join()的调用。 mainloop让您的线程在GC删除BTClient之前完成清理

def update():
    import time
    while thread._keep_alive:
        time.sleep(1)
        print("thread running")

thread = threading.Thread(target=update)
thread._keep_alive = True
thread.start()

最后

thread._keep_alive = False
thread.join()

答案 1 :(得分:0)

所以我在client.t.join()之后添加了行root.mainloop(),这解决了问题,即使我不知道为什么。我认为这是因为python正在破坏tkinter对象,因为在其他线程中仍有对它们的引用,所以等待它们关闭才能解决它。感谢。