Using a thread

In order to use a thread in Python, we can import a module named threading and subclass its Thread class.  Inside our new class, we need to overwrite the run method and perform our logic in there. Once we have done this, we can call the start method on an instance of our class to execute its task in a separate thread.

Let's update our demo application to use a thread. We'll begin by importing the threading module and creating a subclass of Thread:

import tkinter as tk
import time
import threading

class WorkThread(threading.Thread):
def run(self):
label.configure(text="Doing work")
time.sleep(5)
label.configure(text="Finished")

return
...

Our old work function has been moved to the run method of our Thread subclass. This allows it to run in a separate thread when its start method is called.

Speaking of which, we now need to adjust our old work function to make use of this class:

def work():
thread = WorkThread()
thread.start()

In this function, we just make an instance of our WorkThread class and call its start method.

With these changes made, we are now ready to try out our new multithreaded application.

Run this file once again and make sure the Increase Counter button still works. Now, click the Work button and notice how it does not stay pressed in. This time, you will be able to click the Increase Counter button while the application is still working and see the number above increase.

That's how easy it is to integrate a separate thread in a GUI application.

With our new knowledge of how to run a task in the background, we can begin implementing a background task which listens for new messages being sent by a friend in our chat application.

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

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