How to use Thread in Tkinter Python?

With Tkinter, we can call multiple functions simultaneously using Threading. Threading provides asynchronous execution of functions in an application, preventing the GUI from freezing during long-running operations.

To use threading in Python, we import the threading module. The Thread() function allows us to execute functions in separate threads, keeping the main GUI thread responsive.

Basic Threading Example

Let's create a thread that sleeps for 5 seconds while keeping the GUI responsive ?

import tkinter as tk
import time
import threading

# Create the main window
win = tk.Tk()
win.geometry("400x200")
win.title("Threading Example")

# Create label to show status
label = tk.Label(win, text="Click Start to begin", font=("Arial", 12))
label.pack(pady=20)

# Function to run in separate thread
def thread_function():
    label.config(text="Thread is running... Please wait 5 seconds")
    time.sleep(5)
    label.config(text="Thread completed! 5 seconds are up!")

# Function to start the thread
def start_thread():
    # Create and start a new thread
    thread = threading.Thread(target=thread_function)
    thread.start()

# Create start button
start_button = tk.Button(win, text="Start Thread", command=start_thread, 
                        font=("Arial", 12))
start_button.pack(pady=10)

# Create a second button to test GUI responsiveness
test_button = tk.Button(win, text="Test Responsiveness", 
                       command=lambda: label.config(text="GUI is responsive!"),
                       font=("Arial", 12))
test_button.pack(pady=5)

win.mainloop()

Thread with Progress Updates

Here's a more advanced example that updates progress during thread execution ?

import tkinter as tk
from tkinter import ttk
import time
import threading

class ThreadedApp:
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("400x250")
        self.root.title("Advanced Threading")
        
        # Status label
        self.status_label = tk.Label(self.root, text="Ready to start", 
                                   font=("Arial", 12))
        self.status_label.pack(pady=10)
        
        # Progress bar
        self.progress = ttk.Progressbar(self.root, length=300, mode='determinate')
        self.progress.pack(pady=10)
        
        # Buttons
        self.start_btn = tk.Button(self.root, text="Start Long Task", 
                                  command=self.start_long_task)
        self.start_btn.pack(pady=5)
        
        self.stop_btn = tk.Button(self.root, text="Reset", 
                                 command=self.reset_task)
        self.stop_btn.pack(pady=5)
        
        self.running = False
    
    def long_task(self):
        """Simulate a long-running task with progress updates"""
        self.running = True
        for i in range(101):
            if not self.running:
                break
            
            # Update GUI from thread (safe way)
            self.root.after(0, self.update_progress, i)
            time.sleep(0.1)  # Simulate work
        
        if self.running:
            self.root.after(0, lambda: self.status_label.config(text="Task Completed!"))
    
    def update_progress(self, value):
        """Update progress bar and status (called from main thread)"""
        self.progress['value'] = value
        self.status_label.config(text=f"Processing... {value}%")
    
    def start_long_task(self):
        """Start the long task in a separate thread"""
        if not self.running:
            thread = threading.Thread(target=self.long_task)
            thread.daemon = True  # Dies when main thread dies
            thread.start()
    
    def reset_task(self):
        """Reset the task"""
        self.running = False
        self.progress['value'] = 0
        self.status_label.config(text="Ready to start")
    
    def run(self):
        self.root.mainloop()

# Create and run the app
app = ThreadedApp()
app.run()

Key Points

  • GUI Thread Safety: Use root.after() to update GUI elements from worker threads
  • Daemon Threads: Set daemon=True to ensure threads close with the main program
  • Thread Communication: Use thread-safe methods to communicate between threads
  • Avoid Direct GUI Updates: Never update GUI elements directly from worker threads

Common Threading Patterns

Pattern Use Case Example
Fire and Forget Simple background tasks File operations, API calls
Progress Updates Long tasks with feedback File downloads, data processing
Producer-Consumer Continuous data processing Real-time monitoring

Conclusion

Threading in Tkinter keeps your GUI responsive during long-running operations. Always use root.after() to update GUI elements from worker threads, and consider using daemon threads for cleanup.

Updated on: 2026-03-25T16:57:31+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements