How to dynamically add/remove/update labels in a Tkinter window?

We can use the Tkinter Label widget to display text and images. By configuring the label widget, we can dynamically change the text, images, and other properties of the widget.

To dynamically update the Label widget, we can use either config(**options) or an inline configuration method such as for updating the text, we can use Label["text"]=text; for removing the label widget, we can use pack_forget() method.


# Import the required libraries
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image

# Create an instance of tkinter frame or window

# Set the size of the window

def add_label():
   global label
   label=Label(win, text="1. A Newly created Label", font=('Aerial 18'))

def remove_label():
   global label

def update_label():
   global label
   label["text"]="2. Yay!! I am updated"

# Create buttons for add/remove/update the label widget
add=ttk.Button(win, text="Add a new Label", command=add_label)
add.pack(anchor=W, pady=10)

remove=ttk.Button(win, text="Remove the Label", command=remove_label)
remove.pack(anchor=W, pady=10)

update=ttk.Button(win, text="Update the Label", command=update_label)
update.pack(anchor=W, pady=10)


Running the above code will display a window with some buttons in it. Each button can be used to update/remove or add a label in the application.


Upon clicking the "Update the Label" button, the label will get updated as follows −

Updated on: 05-Aug-2021

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started