- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Articles
- How to show and hide widgets in Tkinter?
- How to reconfigure Tkinter canvas items?
- How to bind events to Tkinter Canvas items?
- How to get coordinates on scrollable canvas in Tkinter?
- How to create a Button on a Tkinter Canvas?
- How to open PIL Image in Tkinter on Canvas?
- How to draw a line on a Tkinter canvas?
- How to draw an arc on a tkinter canvas?
- How to put an outline on a canvas text on Tkinter?
- Tkinter - How to put an outline on a canvas text
- How to draw a dashed line on a Tkinter canvas?
- How to clear Tkinter Canvas?
- How can I show and hide div on mouse click using jQuery?
- How do I update images on a Tkinter Canvas?
- How to draw a png image on a Python tkinter canvas?
