Catching exceptions in Tkinter's mainloop

Mike Callahan mcalla at home.com
Fri Mar 16 17:13:15 EST 2001


I want to make sure that if any exception pops up inside a mainloop, that
exception is printed to a log file and the mainloop quits. I tried to
simulate this with the following code but failed:

from Tkinter import *

class Gui:
    def __init__(self, master):
        self.master = master
        self.button = Button(master, text='Crash', command=self.crash)
        self.button.pack()

    def crash(self):
        z = zz  # trigger exception

root = Tk()
app = Gui(root)
try:
    root.mainloop()
except:
    print 'caught'
    root.quit()

It doesn't work. The exception is printed out by standard traceback and the
mainloop continues. What am I doing wrong?

Mike Callahan







More information about the Python-list mailing list