Re: tkinter, problems destroying widgets

Guido.van.Rossum@cwi.nl
Wed, 29 Mar 1995 11:53:22 +0200

> I have problems getting a widget to exit and destroy
> itself properly sometimes. I have no idea what causes the problem
> -- it seems random to me.
>
> Here is a code fragment that makes a highest frame with a
> "start" and "end" button.
> =========
> # start up script for tk interface to sql interpreter
> # borrows heavily from guido's dialog.py
> def main():
> from Tkinter import *
> global mainWidget
> mainWidget = Frame()
> Pack.config(mainWidget)
> labl = Label(mainWidget, {"text": "Welcome to tkDB"})
> labl.pack()
> start = Button(mainWidget,
> {"text": "Load SQL and go", "command": go})
> start.pack()
> endit = Button(mainWidget,
> {"text": "exit",
> "command": terminate,
> Pack: {"fill":"both"}})
> mainWidget.messagearea = None
> mainWidget.LOADED = 0
>
> # is this right?
> def terminate():
> import sys
> # do cleanup actions...
> sys.exit()
>
> def go():... do something complicated....
> =================
> The above is actually just the last of several attempts to remove this
> problem.
>
> Now, I thought that pressing the "exit" button any time should
> terminate the whole tree of widgets, but sometimes it seems to do
> nothing -- even if everything else has been terminated normally (as
> far as I can see, anyway). I see this for other widgets also.
> Someone tell me what I'm missing, or tell me what I should read,
> please.

Hm. That *should* work, but there are some fishy things with
exception handling in older versions of tkinter and Tkinter, so maybe
that's biting you. (sys.exit() doesn't actually call exit(), it
raises an exception SystemExit.) (I hope you haven't forked a
subprocess which might hold on to your X server connection?)

I must admit I can't remember this for sure myself, and I can't test
it out currently, but I think the proper way to quit is to call the
quit() method from the same widget whose mainloop() widget you started
(usually the root). If all fails, try os._exit(0) -- this makes the
_exit() system call. Oh, the root widget also has a destroy() method
which should recursively get rid of all widgets...

You see, plenty of opportunities for learning...

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>