Starting a thread
This recipe will show us how to start a thread. It will also demonstrate why threads are necessary to keep our GUI responsive during long-running tasks.
Getting ready
Let's first see what happens when we call a function or method of our GUI that has some sleep associated with it without using threads.
Note
We are using a sleep here to simulate a real-world application that might have to wait for a web server or database to respond or a large file transfer or complex computation to complete its task.
The sleep is a very realistic place-holder and shows the principle involved.
Adding a loop into our button callback method with some sleep time results in our GUI becoming unresponsive and, when we try to close the GUI, things get even worse.
# Button callback def clickMe(self): self.action.configure(text='Hello ' + self.name.get()) # Non-threaded code with sleep freezes the GUI for idx in range(10): sleep(5) self.scr.insert(tk.INSERT, str(idx) + '\n')
If we wait long...