How to hide and show canvas items on Tkinter?


The Canvas widget is one of the versatile widgets in Tkinter. It is used in many applications for designing the graphical user interface such as designing, adding images, creating graphics, etc. We can add widgets in the Canvas widget itself. The widgets that lie inside the canvas are sometimes called "Canvas Items".

If we want to show or hide the canvas items through a Button, then this can be achieved by using the "state" property in itemconfig(id, state) method.

Example

In this example, we will add an image in the canvas and a button will be used to show/hide the image in the canvas.

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

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

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

# Globally Declare the Boolean value
show = True

def on_click():
   global show

   # Determine if the image is hidden or not
   if show:
      canvas.itemconfig(1, state='hidden')
      show = False
   else:
      canvas.itemconfig(1, state='normal')
      show = True

# Add a Canvas widget
canvas = Canvas(win, width=440, height=300)
canvas.pack()

# Add image to the canvas
img = ImageTk.PhotoImage(file="bird.jpg")
canvas.create_image(200, 200, image=img, anchor=CENTER)

# Add a Button to Show/Hide Canvas Items
ttk.Button(win, text="Show/Hide", command=on_click).pack()

win.mainloop()

Output

If we run the above code, it will display a window with an image and a button to trigger the function for hiding and showing the image.

Now, click the button to show/hide the image.

Updated on: 19-Jun-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements