Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to clear Tkinter Canvas?
Tkinter provides a way to add a canvas in a window, and when we create a canvas, it wraps up some storage inside the memory. While creating a canvas in Tkinter, it will effectively eat some memory which needs to be cleared or deleted.
In order to clear a canvas, we can use the delete() method. By specifying "all", we can delete and clear all the canvas objects that are present in a Tkinter frame.
Syntax
canvas.delete("all")
Where canvas is your canvas object and "all" removes all items from the canvas.
Example
Let's create a canvas with an arc and then clear it using the delete() method ?
# Import the tkinter library
from tkinter import *
# Create an instance of tkinter frame
win = Tk()
# Set the geometry
win.geometry("650x250")
# Creating a canvas
myCanvas = Canvas(win, bg="white", height=200, width=200)
coordinates = 10, 10, 200, 200
arc = myCanvas.create_arc(coordinates, start=0, extent=320, fill="red")
myCanvas.pack()
# Print canvas items before clearing
print("Canvas items before clearing:", myCanvas.find_all())
# Clearing the canvas
myCanvas.delete('all')
# Print canvas items after clearing
print("Canvas items after clearing:", myCanvas.find_all())
win.mainloop()
The output of the above code is ?
Canvas items before clearing: (1,) Canvas items after clearing: ()
Clearing Specific Items
You can also clear specific items by passing their item IDs instead of "all" ?
from tkinter import *
win = Tk()
win.geometry("400x300")
canvas = Canvas(win, bg="lightgray", height=200, width=300)
# Create multiple items
circle = canvas.create_oval(50, 50, 150, 150, fill="blue")
rectangle = canvas.create_rectangle(200, 50, 280, 120, fill="green")
line = canvas.create_line(10, 180, 290, 180, width=3)
canvas.pack()
# Delete only the circle
canvas.delete(circle)
print("Remaining items:", canvas.find_all())
win.mainloop()
The output shows the remaining items after deleting the circle ?
Remaining items: (2, 3)
Common Use Cases
- Animation: Clear canvas before drawing the next frame
- Drawing apps: Implement "Clear All" functionality
- Games: Reset the game board
- Data visualization: Update charts and graphs
Comparison
| Method | Description | Use Case |
|---|---|---|
delete("all") |
Removes all canvas items | Complete canvas reset |
delete(item_id) |
Removes specific item | Selective deletion |
find_all() |
Returns all item IDs | Check canvas contents |
Conclusion
Use canvas.delete("all") to clear all items from a Tkinter canvas. For selective deletion, use the specific item ID returned when creating canvas objects.
