Tkinter Canvas Items - not ref counted?

Charles G Waldman cgw at fnal.gov
Mon May 3 14:51:40 EDT 1999


Randall Hopper writes:
 >      Why does the Canvas Rectangle and its canvas item not get destroyed
 > using the following fragment:
 > 
 >  from Tkinter import *
 >  from Canvas import *
 >  root = Tk()
 >  canvas = Canvas( root )
 >  canvas.pack()
 >  rect = Rectangle( canvas, 1, 1, 100, 100 )
 >  rect = None                                  # <--- Destroy it here
 >  root.update_idletasks()
 > 
 > You can see the rectangle even after the "rect = None" executes.
 > 
 > Randall


Tkinter objects aren't behaving the way you expect.

The line "rect = Rectangle( canvas, 1, 1, 100, 100)"
causes a rectangle to be created (the call to Rectangle) and it's ID
to be stored in the variable "rect".  Subsequently doing "rect = None" 
gets rid of the ID but doesn't undo the effect of creating the
rectangle - you've just deleted it's handle, not the object itself.

Part of the reason this is confusing has to do with the fact that
Python and Tk each have their own object hierarchy.

If you want to erase the rectangle drawn on the canvas, try:

 canvas.delete(rect)

Hope this helps,

     -cgw




More information about the Python-list mailing list