How to update the image of a Tkinter Label widget?

TkinterServer Side ProgrammingProgramming

We have used Label widget to group all the widgets in the application. A Label widget takes text and images in the constructor that sets the label with the position in the top-left corner of the window. However, to change or update the image associated with the Label, we can use a callable method where we provide the information of other images.

Example

In the following example, we will create a button to update the Label image.

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

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

#Define geometry of the window
win.geometry("750x600")
win.title("Gallery")

#Define a Function to change to Image
def change_img():
   img2=ImageTk.PhotoImage(Image.open("tutorialspoint.png"))
   label.configure(image=img2)
   label.image=img2

#Convert To PhotoImage
img1= ImageTk.PhotoImage(Image.open("logo.png"))

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

#Create a Button to handle the update Image event
button= Button(win, text= "Change", font= ('Helvetica 13 bold'),
command= change_img)
button.pack(pady=15)
win.bind("<Return>", change_img)
win.mainloop()

Output

Running the example code will display a window with a Label Image and a button that helps to change the label image.

Now, just click the "Change" button to update the Label Image.

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