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 while 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. For example,

data = ['Car', 'Bus', 'Truck', 'Bike', 'Airplane']

var = StringVar(win)

my_spinbox = Spinbox(win, values=data, textvariable=var)

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().

Example

The following example demonstrates how you can update a tkinter label using a while loop −

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x300")

# Initialize a StringVar
var = StringVar()

def label_update():
   num = 0
   while 1:
      # Update the StringVar
      num = num + 1
      var.set("Count up to: " + str(num))
      win.after(200, win.update())

      if num==100:
         break

# Create a label widget
label = Label(win, textvariable=var, font='Arial 17 bold')
label.pack(pady=20)

button = Button(win, text="Count", command=label_update)
button.pack()

win.mainloop()

Output

On execution, the program would display the following window −

On clicking the "Count" button, it will display a Label widget and start updating its value until it becomes 100.

Updated on: 05-Sep-2023

593 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements