How to use Thread in Tkinter Python
Prerequisite:
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.
While Creating a GUI there will be a need to do multiple work/operation at backend. Suppose we want to perform 4 operations simultaneously. The problem here is, each operation executes one by one. During execution of one operation the GUI window will also not move and this is why we need threading. Both implementation is given below which obviously will help understand their differences better.
Without Threading
Working without threads, makes the process delayed. Also, the window will not move until full execution takes place.
Approach
- Create Normal Tkinter Window
- Add Button with command
- Execute Tkinter
Program:
Python3
from tkinter import *
import time
from threading import *
root = Tk()
root.geometry( "400x400" )
def work():
print ( "sleep time start" )
for i in range ( 10 ):
print (i)
time.sleep( 1 )
print ( "sleep time stop" )
Button(root, text = "Click Me" , command = work).pack()
root.mainloop()
|
Output:
With Threading
Approach
- Create Normal Tkinter Window
- Add Button with command for threading
- Execute Tkinter
Program:
Python3
from tkinter import *
import time
from threading import *
root = Tk()
root.geometry( "400x400" )
def threading():
t1 = Thread(target = work)
t1.start()
def work():
print ( "sleep time start" )
for i in range ( 10 ):
print (i)
time.sleep( 1 )
print ( "sleep time stop" )
Button(root,text = "Click Me" ,command = threading).pack()
root.mainloop()
|
Output:
Last Updated :
17 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...