How to use Thread in Tkinter Python?


With Tkinter, we can call multiple functions at a time using Threading. It provides asynchronous execution of some functions in an application.

In order to use a thread in Python, we can import a module called threading and subclass its Thread class. Inside our new class, we need to overwrite the Run method and perform our logic in there.

So, basically with threading, we can do multiple work at a time. To achieve threading in our application, Tkinter provides the Thread() function.

Let us take an example and create a thread which will sleep for some time and then execute another function in parallel.

For this example, we will import the Time module and the threading module defined in the Tkinter library.

Example

#Import all the necessary libraries
from tkinter import *
import time
import threading

#Define the tkinter instance
win= Tk()

#Define the size of the tkinter frame
win.geometry("700x400")

#Define the function to start the thread
def thread_fun():
   label.config(text="You can Click the button or Wait")
   time.sleep(5)
   label.config(text= "5 seconds Up!")
   
label= Label(win)
label.pack(pady=20)
#Create button
b1= Button(win,text= "Start", command=threading.Thread(target=thread_fun).start())
b1.pack(pady=20)

win.mainloop()

Output

Running the above code will create a button and a thread which works on a label.

After 5 seconds, the thread will automatically pause.

Updated on: 06-Mar-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements