Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear Tkinter Canvas?

When I draw a shape using:

canvas.create_rectangle(10, 10, 50, 50, color="green") 

Does Tkinter keep track of the fact that it was created?

In a simple game I'm making, my code has one Frame create a bunch of rectangles, and then draw a big black rectangle to clear the screen, and then draw another set of updated rectangles, and so on.

Am I creating thousands of rectangle objects in memory?

I know you can assign the code above to a variable, but if I don't do that and just draw directly to the canvas, does it stay in memory, or does it just draw the pixels, like in the HTML5 canvas?

like image 938
Taylor Hill Avatar asked Apr 05 '13 17:04

Taylor Hill


People also ask

How do you clear a python canvas?

Create the widget adding the argument tags='my_tag' . Then when you want to clear the screen you can do canvas. delete('my_tag') . All canvas widgets tagged with 'my_tag' will be deleted.

How do you clear the screen in tkinter?

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 that are present in a tkinter frame.


2 Answers

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.

like image 157
Bryan Oakley Avatar answered Sep 18 '22 09:09

Bryan Oakley


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, and move to modify the items, or use delete to remove them.

like image 22
Steven Rumbalski Avatar answered Sep 20 '22 09:09

Steven Rumbalski