[Tutor] Tkinter mainloop (was Re: tkFileDialog.Directory)

Kent Johnson kent37 at tds.net
Wed Nov 16 14:00:41 CET 2005


K.Weinert at gmx.net wrote:
> What I don't understand is
>>>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.
 
> 
> I thought the mainloop() function is something like
> 
> def mainloop():
>   e= get_event()
>   if e:
>     for w in widgets: w.handle(e)
> 
> but apparently it is not.

The main loop is probably more like this:
def mainloop():
  e= get_event()
  if e:
    try:
      for w in widgets: w.handle(e)
    except:
      traceback.print_exc()

It's pretty common for GUI toolkits to trap exceptions in the event handler. This can help make a more robust application - in my experience I don't really want a bug in a handler to crash the whole app.

There is an undocumented hook that lets you change this - the function Tk.report_callback_exception() is called to actually report the error. You can redefine this function to do what you want. Here are a couple of examples:
http://zephyrfalcon.org/weblog/arch_d7_2003_01_04.html
http://groups.google.com/group/comp.lang.python/browse_thread/thread/ce0036f41da8a22f/c62177e5bb59b09c%23c62177e5bb59b09c?sa=X&oi=groupsr&start=1&num=3

Kent

-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list