Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python: How to update tkinter labels using a loop?
We normally use the Tkinter Label widget to display text and images in an application. Let us assume that we want to create an application such that the Label widget continuously gets updated with a value whenever the application executes. To achieve this, we will use a StringVar object and update its value using a loop that will iterate as long as a particular condition satisfies.
A StringVar object in Tkinter can help manage the value of a widget such as an Entry widget or a Label widget. You can assign a StringVar object to the textvariable of a widget.
Understanding StringVar
Here's how to use StringVar with widgets ?
from tkinter import *
root = Tk()
root.geometry("300x200")
data = ['Car', 'Bus', 'Truck', 'Bike', 'Airplane']
var = StringVar(root)
my_spinbox = Spinbox(root, values=data, textvariable=var)
my_spinbox.pack(pady=20)
# Get current value
def show_value():
print("Current value:", var.get())
button = Button(root, text="Show Value", command=show_value)
button.pack()
root.mainloop()
Here, we created a list of strings followed by a StringVar object "var". Next, we assigned var to the textvariable of a Spinbox widget. To get the current value of the Spinbox, you can use var.get().
Method 1: Using after() for Nonblocking Updates
The recommended approach uses after() to schedule updates without blocking the GUI ?
from tkinter import *
# Create an instance of tkinter frame
win = Tk()
win.geometry("700x300")
# Initialize a StringVar
var = StringVar()
var.set("Click 'Start Count' to begin")
# Counter variable
count = 0
def update_label():
global count
count += 1
var.set("Count up to: " + str(count))
# Schedule next update if count < 100
if count < 100:
win.after(200, update_label) # Update every 200ms
else:
var.set("Counting finished!")
def start_counting():
global count
count = 0
update_label()
# Create a label widget
label = Label(win, textvariable=var, font='Arial 17 bold')
label.pack(pady=20)
button = Button(win, text="Start Count", command=start_counting)
button.pack()
win.mainloop()
Method 2: Using Threading for Complex Operations
For more complex operations, you can use threading to avoid blocking the main GUI thread ?
from tkinter import *
import threading
import time
win = Tk()
win.geometry("700x300")
var = StringVar()
var.set("Ready to start")
def threaded_update():
for i in range(1, 101):
var.set(f"Processing: {i}%")
time.sleep(0.1) # Simulate work
var.set("Processing complete!")
def start_process():
# Run in separate thread to avoid blocking GUI
thread = threading.Thread(target=threaded_update)
thread.daemon = True # Dies when main program exits
thread.start()
label = Label(win, textvariable=var, font='Arial 17 bold')
label.pack(pady=20)
button = Button(win, text="Start Process", command=start_process)
button.pack()
win.mainloop()
Key Points
- StringVar objects automatically update connected widgets when their value changes
- Use
after()for simple periodic updates it's nonblocking - Avoid
whileloops in GUI callbacks as they freeze the interface - Use threading for longrunning operations that need to update the GUI
- Always use
daemon=Truefor background threads in GUI applications
Comparison
| Method | Blocks GUI? | Best For |
|---|---|---|
after() |
No | Simple periodic updates |
| Threading | No | Complex operations |
| While loop | Yes | Not recommended |
Conclusion
Use after() for simple label updates and threading for complex operations. Avoid blocking loops that freeze the GUI. StringVar provides automatic widget updates when values change.
