Python Tkinter GUI Tutorial #97: Threading with Tkinter

Posted by


In this tutorial, we will be learning about threading with Tkinter in Python. Threading is a powerful way to keep your GUI responsive while performing time-consuming tasks in the background. Tkinter is a popular GUI toolkit for Python, and by combining it with threading, we can create more responsive and efficient applications.

To start off, make sure you have Tkinter installed on your system. Tkinter comes pre-installed with Python, so you should already have it. If not, you can install it using pip:

pip install tk

Now, create a new Python file and import the necessary modules:

import tkinter as tk
from tkinter import messagebox
import threading

Next, let’s create a simple Tkinter application with a button that performs a time-consuming task when clicked:

def long_task():
    # Simulate a time-consuming task
    for i in range(5):
        print("Task running...")
        time.sleep(1)
    print("Task completed!")

def on_click():
    # Start a new thread to perform the task
    thread = threading.Thread(target=long_task)
    thread.start()

root = tk.Tk()
root.title("Threading with Tkinter")

button = tk.Button(root, text="Start Task", command=on_click)
button.pack()

root.mainloop()

In this code, we have defined a long_task function that simulates a time-consuming task by printing messages every second. The on_click function starts a new thread to run the long_task function when the button is clicked.

Now, when you run the code and click the button, you will see the messages "Task running…" printed every second until the task is completed.

It’s important to note that Tkinter is not thread-safe, meaning that you should not update the GUI from a different thread than the main one. If you need to update the GUI from a thread, you can use the after method to schedule the update on the main thread:

def update_label(text):
    label.config(text=text)

def long_task():
    for i in range(5):
        update_label("Task running...")
        time.sleep(1)
    update_label("Task completed!")

root = tk.Tk()
root.title("Threading with Tkinter")

label = tk.Label(root, text="")
label.pack()

button = tk.Button(root, text="Start Task", command=on_click)
button.pack()

root.mainloop()

In this code, we have defined an update_label function that updates the label text. We call this function from the long_task function to update the label text on the main thread.

Threading with Tkinter can be a powerful tool to keep your GUI responsive while performing time-consuming tasks in the background. Just be sure to use threading carefully to avoid thread safety issues. Experiment with threading in your Tkinter applications and see how you can improve their performance and responsiveness.

0 0 votes
Article Rating

Leave a Reply

43 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Codemycom
2 hours ago

▶️ Watch Entire Tkinter Playlist ✅ Subscribe To My YouTube Channel:
http://bit.ly/2UFLKgj http://bit.ly/2IGzvOR
▶️ See More At: ✅ Join My Facebook Group:
https://Codemy.com http://bit.ly/2GFmOBz
▶️ Learn to Code at https://Codemy.com ✅ Buy a Codemy T-Shirt!
Take $30 off with coupon code: youtube1 http://bit.ly/2VC9WUN
▶️ Get The Code
https://bit.ly/3fLFQ8p

@64bitMario
2 hours ago

Great guide! Now I'll never forget to give a widget pady=20 to push it down a little bit.

@workingyabs5683
2 hours ago

imagine showing the codes instead of zooming in to show it one little part at a time

@kingsleyjide4486
2 hours ago

what about for multiprocessing, why does it create new instances of the app

@xreed8
2 hours ago

You could definitely use time.sleep() in a pyqt/tkinter/etc program. For example, typically web scraping projects will, at some point no matter what you do, require you to use time.sleep() in order to accommodate unexpected connection issues, HTML DOM lag, network lag, etc.

@frankrogowski9595
2 hours ago

Wow this is excellent! I am developing a FinTech payment processing application and I am at the point where threading is very necessary. So simple. Great teacher-instructor. Thank you! Going to to apply this to my notebook/tabs where my application is split out logically and may hang the rest of the program if a single threaded. Love these series of Tkinter. Wish I would have found these a 1yr ago. I am now a Tkinter junkie.

@bob1784free
2 hours ago

Is Tkinter thread safe ?

@alexvillegas8155
2 hours ago

You are a genius ! Thank you so much !

@jaipreetsingh304
2 hours ago

Thank you for this video, but what if I want to send parameters like root(which is tkinter object) into five_seconds(root). Will it behave the same, I tried to do so but it is not running together. I tried args but it is not able to send root object to other function. Kindly Help

@ztech3401
2 hours ago

hey can you solve this problem please

RuntimeError: There is no current event loop in thread 'Thread-1'.

@tamasvida6454
2 hours ago

many thanks dude FINALLY i was able to fix my code after 2 month of trying D:

@BWNL_BILL
2 hours ago

i am getting a problem with my code whenever i run my code it will immediately run the thread freezing my code until its done waiting

@vihangamohottige6528
2 hours ago

Thank you…

@parasgtr1984
2 hours ago

how to make button that stops the thread?

@nebular-nerd
2 hours ago

A super simple explanation that works, top stuff!

@filipemarques4091
2 hours ago

How can i use threading to mix song 1 and song 2, decreasing the volume of song 1 in the end and increasing the volume of song 2 in the begining?

@flydr2
2 hours ago

Many thanks…. very well explained

@julicojotase
2 hours ago

Thank you so much i had a headache with opencv, trying to get still the camera frame

@rudnat3003
2 hours ago

Thanks a lot! It helped me!

@abdelafnin8843
2 hours ago

👍

43
0
Would love your thoughts, please comment.x
()
x