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?