[Tutor] Tkinter - Destroying windows, destroying widgets

Michael P. Reilly arcege@shore.net
Sun, 4 Feb 2001 09:00:36 -0500 (EST)

> This is a multi-part message in MIME format.
> ------=_NextPart_000_0015_01C08F02.2F800700
> Content-Type: text/plain;
> 	charset="iso-8859-1"
> Content-Transfer-Encoding: quoted-printable
>   Hey all,
>   I was just writing up a little tkinter app (a game, actually) and I =
> have hit a wall.  My predicament, is that I want to destroy an object =
> (right word?) but I want to do it in a function...for example in this =
> code :
> from Tkinter import *
> def die():
>     l.destroy() ## here is the problem - root.l.destroy() does not work =
> either - I think since variables are local in functions it doesn't have =
> any clue as to the existence of the label "l"
>     print 'yo'    =20
>     raw_input("hi")
> root =3D Tk()
> root.title('jim')
> l =3D Label(root, text=3D'hi im root').pack()
> second =3D Toplevel(root)
> b =3D Button(root, text=3D'yo', command=3Ddie).pack()
> mainloop()
>   No matter how hard I try I cannot kill the label "l" using the button, =
> and have it do other things as well.  Say I wanted to destroy a widget =
> in a different window??  That label is in the same toplevel.  I just =
> know there is a way to say something akin to "In the widget 'root' is a =
> widget 'l' - kill it" but for the life of me I cannot find it.  You =
> can't pass a widget as an argument using lambda, either - I tried tho :)
>   I've looked in John Grayson's book and the python docs but I can't =
> find anything.  Help!

You have the right idea, but if you print "l", it is set to None, not
to an object.  That is because the pack() method returns None.  You
will want to use:
  l = Label(root, text = 'hi im root')

I would suggest however, creating a class (often a subclass of Frame)
to represent what you want, setting attributes for the widgets that you
wish to access later:

  class SpamEggs(Frame):
    def __init__(self, master=None, labeltxt='', buttontxt=''):
      Frame.__init__(self, master)
      self.l = Label(self, text=labeltxt)
      self.b = Button(self, text=buttontxt, command=self.die)
    def die(self):
      if self.l:
      self.l = None # so we do not destroy it twice

  root = Tk()
  SpamEggs(root, 'hi im root', 'yo').pack()

Good luck,

| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |