How to clear Tkinter Canvas?
Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.
To clear a canvas, use the delete method. Give it the special parameter "all"
to delete all items on the canvas (the string "all"
" is a special tag that represents all items on the canvas):
canvas.delete("all")
If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all"
, you could supply the name of a tag.
If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.
Items drawn to the canvas are persistent. create_rectangle
returns an item id that you need to keep track of. If you don't remove old items your program will eventually slow down.
From Fredrik Lundh's An Introduction to Tkinter:
Note that items added to the canvas are kept until you remove them. If you want to change the drawing, you can either use methods like
coords
,itemconfig
, andmove
to modify the items, or usedelete
to remove them.
Yes, I believe you are creating thousands of objects. If you're looking for an easy way to delete a bunch of them at once, use canvas tags described here. This lets you perform the same operation (such as deletion) on a large number of objects.