__del__ in classes derived from Tkinter classes

Fredrik Lundh fredrik at pythonware.com
Thu Jul 18 12:07:13 EDT 2002


Petr Klyushkin wrote
> I'm a Python and Tkinter newbie.  I've noticed that __del__ methods of
> my classes derived from Tkinter classes are never called.  Is this
> normal behavior, or I am doing something wrong?
>
> Example code:
>
> import Tkinter
>
> class Test(Tkinter.Toplevel):
>   def __del__(self):
>     print 'hey!'
>
> tk = Tkinter.Tk()
> test = Test(tk)

tkinter maintains an internal widget tree.  if you want to
print "hey" when your toplevel widget is destroyed, over-
ride the "destroy" method:

    class Test(Tkinter.Toplevel):
        def destroy(self):
            Tkinter.Toplevel.destroy(self)
            print 'hey!'

if you want to capture attempts to close the window, you
should install a WM_DELETE_WINDOW protocol handler; for
details, see:

    http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm

(and using __del__ is usually bad style even outside Tkinter,
but that's another story).

</F>





More information about the Python-list mailing list