How to update a Python/tkinter label widget?

TkinterServer Side ProgrammingProgramming

Tkinter comes with a handy built-in functionality to handle common text and images related objects. A label widget annotates the user interface with text and images. We can provide any text or images to the label widget so that it displays in the application window.

Let us suppose that for a particular application, we need to update the label widget. A label widget is a container that can have either text of image. In the following example, we will update the label image by configuring a button.

Example

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

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

#Define geometry of the window
win.geometry("750x450")

#Define a Function to update to Image
def update_img():
   img2=ImageTk.PhotoImage(Image.open("logo.png"))
   label.configure(image=img2)
   label.image=img2

#Load the Image
img1= ImageTk.PhotoImage(Image.open("logo1.png"))

#Create a Label widget
label= Label(win,image= img1)
label.pack()

#Create a Button to handle the update Image event
button= ttk.Button(win, text= "Update", command= update_img)
button.pack(pady=15)
win.bind("<Return>", update_img)

win.mainloop()

Output

Running the above code will display a window that contains a label with an image. The Label image will get updated when we click on the “update” button.

Now, click the "Update" button to update the label widget and its object.

raja
Published on 16-Apr-2021 07:08:02
Advertisements