Removing an Image in a Label in Tkinter?
To remove an image inside the Label widget in Tkinter, we use the config() method. This method takes an image parameter. If you want to remove the image, just assign empty double quotes as the value for the image parameter.
Let us see a few example code below to understand better how this works.
Removing an Image in a Label
Removing an image means, that when the button is clicked, the image will disappear from the window leaving an empty space.
Example: In this example, we will create a simple Tkinter window which contains an image as a label and a button. On clicking the button, the image label should be removed/deleted from the window.
# Importing tkinter
import tkinter as tk
# Function to remove image from Label
# on clicking the button 'removeImageButton'.
def remove_image():
label1.config(image="")
# GUI creation
root = tk.Tk()
root.geometry("300x200")
root.title("w3wiki")
# image is converted to PhotoImage variable
apple_picture = tk.PhotoImage(file="image_path")
# Label created with image
label1 = tk.Label(root, image=apple_picture)
label1.pack(pady=20)
# Button created to remove the image
# from the Label widget 'label1'
removeImageButton = tk.Button(
root, text="Remove image",
command=remove_image,
bg="green", fg="white")
removeImageButton.pack()
root.mainloop()
Output:
Replacing an Image in a Label
Replacing an image means, that when the button is clicked, the original image will disappear or get removed from the window and a new image will appear. The config() method will now have the new PhotoImage object, that is the new image, and the label widget’s image attribute is also replaced with the new image.
Example: In this example, we will create a simple Tkinter window which contains an image as that label and a button. On clicking the button, the image label should be replaced by another image on the window.
# Importing tkinter
import tkinter as tk
# Function to replace image from Label
# on clicking the button 'replaceImageButton'
def replace_image():
new_image = tk.PhotoImage(file="image_path")
label1.config(image=new_image)
label1.image = new_image
# GUI creation
root = tk.Tk()
root.geometry("300x200")
root.title("w3wiki")
# image is converted to PhotoImage variable
apple_picture = tk.PhotoImage(file="image_path")
# Label created with image
label1 = tk.Label(root, image=apple_picture)
label1.pack(pady=20)
# Create a button to replace the image
replaceImageButton = tk.Button(root,
text="Replace Image",
command=replace_image)
replaceImageButton.pack()
root.mainloop()
Output:
Remove An Image In A Label In Tkinter
Tkinter is a GUI-creating module in Python that is used to create many applications. It has many useful widgets such as Label, Checkbutton, Button, Checkbox, and more. In this article, we will discuss how we can remove an image from the Label widget in Tkinter in Python.