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.


#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

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



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

After 5 seconds, the thread will automatically pause.

Published on 06-Mar-2021 08:47:34