Mailing List Archive

Tkinter Canvas Items - not ref counted?
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 Canvas Items - not ref counted? [ In reply to ]
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
Tkinter Canvas Items - not ref counted? [ In reply to ]
Charles G Waldman:
|Randall Hopper writes:
| > Why does the Canvas Rectangle and its canvas item not get destroyed
| > using the following fragment:
...
| > rect = Rectangle( canvas, 1, 1, 100, 100 )
| > rect = None # <--- Destroy it here
...
|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)

Thanks. It doesn't seem completely intuitive that creating a Tk "shadow"
class creates a widget or canvas item, but deleting the Tk shadow class
doesn't delete the widget or canvas item. But I'll accept that as how it
works.

Randall