Getting ready

Let's first see what happens when we call a function or a method of our GUI that has some sleep associated with it without using threads.

We are using sleep here to simulate a real-world application that might have to wait for a web server or database to respond, a large file transfer, or complex computations to complete its task.
sleep is a very realistic placeholder 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:
GUI_multiple_threads_sleep_freeze.py

    # Button callback
def click_me(self):
self.action.configure(text='Hello ' + self.name.get() + ' '
+ self.number_chosen.get())
# Non-threaded code with sleep freezes the GUI
for idx in range(10):
sleep(5)
self.scrol.insert(tk.INSERT, str(idx) + 'n')

Running the preceding code file results in the following screenshot:

If we wait long enough, the method will eventually complete, but during this time, none of our GUI widgets respond to click events. We solve this problem by using threads.

In the previous recipe, we created a method to be run in a thread but, so far, the thread has not run!

Unlike regular Python functions and methods, we have to start a method that will be run in its own thread!

This is what we will do next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.29.22