First, let's move the creation of the thread into its own method and then call this method from the button callback method:
# Running methods in Threads
def create_thread(self):
self.run_thread = Thread(target=self.method_in_a_thread)
self.run_thread.start() # start the thread
# Button callback
def click_me(self):
self.action.configure(text='Hello ' + self.name.get())
self.create_thread()
Clicking the button now results in the create_thread method being called, which, in turn, calls the method_in_a_thread method.
First, we create a thread and target it at a method. Next, we start the thread that runs the targeted method in a new thread:
We can print out the instance of the thread:
GUI_multiple_threads_thread_in_method.py
# Running methods in Threads
def create_thread(self):
self.run_thread = Thread(target=self.method_in_a_thread)
self.run_thread.start() # start the thread
print(self.run_thread)
Clicking the button now creates the following printout:
When we click the button several times, we can see that each thread gets assigned a unique name and ID:
Let's now move our code with sleep in a loop into the method_in_a_thread method to verify that threads really do solve our problem:
def method_in_a_thread(self):
print('Hi, how are you?')
for idx in range(10):
sleep(5)
self.scrol.insert(tk.INSERT, str(idx) + 'n')
When clicking the button, while the numbers are being printed into the ScrolledText widget with a five second delay, we can click around anywhere in our GUI, switch tabs, and so on. Our GUI has become responsive again because we are using threads!
GUI_multiple_threads_starting_a_thread.py