Friday, December 27, 2024
Google search engine
HomeLanguagesHow to use Thread in Tkinter Python

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




# Import Module
from tkinter import *
import time
from threading import *
  
# Create Object
root = Tk()
  
# Set geometry
root.geometry("400x400")
  
  
def work():
  
    print("sleep time start")
  
    for i in range(10):
        print(i)
        time.sleep(1)
  
    print("sleep time stop")
  
  
# Create Button
Button(root, text="Click Me", command=work).pack()
  
# Execute Tkinter
root.mainloop()


Output:

With Threading

Approach

  • Create Normal Tkinter Window
  • Add Button with command for threading 
  • Execute Tkinter

Program:

Python3




# Import Module
from tkinter import *
import time
from threading import *
  
# Create Object
root = Tk()
  
# Set geometry
root.geometry("400x400")
  
# use threading
  
def threading():
    # Call work function
    t1=Thread(target=work)
    t1.start()
  
# work function
def work():
  
    print("sleep time start")
  
    for i in range(10):
        print(i)
        time.sleep(1)
  
    print("sleep time stop")
  
# Create Button
Button(root,text="Click Me",command = threading).pack()
  
# Execute Tkinter
root.mainloop()


Output:

RELATED ARTICLES

Most Popular

Recent Comments