[Tutor] tkFileDialog.Directory

Michael Lange klappnase at freenet.de
Tue Nov 15 19:06:38 CET 2005

On Tue, 15 Nov 2005 17:03:24 +0100 (MET)
K.Weinert at gmx.net wrote:

> I would like to ask another question. I don't understand the exception
> mechanism
> of Python when running a Tkinter app. If an exception happens (it does
> happen quite often
> at the moment..), a traceback is written to the console while the Tk window
> remains open
> and the application is still running. This is not what I expected -- I
> expected the application
> would end. Why is that?
> Is there a way to create an error handler for uncaught exceptions in Tkinter
> apps?
> In other words, can I change the behaviour from writing a traceback to the
> console to
> something else? Can I, for example, show a message box instead?

If you only want to see the traceback in your gui, I recommend using Pmw.
Pmw pops up a Text window that shows the complete traceback, it doesn't catch the exception though.

> Here is a small example:
> --- snip ---  
> import Tix
> def raise_exception():
>   print 1/0
> if __name__ == '__main__':
>     root = Tix.Tk()
>     root.title("Exception demo")
>     Tix.Button(root, text = "Don't press", command = raise_exception).pack()
>     try:
>       root.mainloop()
>     except:
>       print "An error has occured."
> --- snip ---
> The except part gets never executed.

That's because the error isn't in the mainloop() method.
Probably you meant something like

def raise_exception():
        print 1 / 0
    except ZeroDivisionError:
        print "An error has occured."
        # or with a message box:
        # tkMessageBox.showerror(message='ZeroDivisionError')


Thank god python is nice enough to raise the error where it actually happens;
imagine your example would work, you would never know *where* the error happened
nor could you create adequate handlers for different exceptions in different situations.

I hope this helps


More information about the Tutor mailing list