Tkinter and exceptions

Nick Craig-Wood nick at craig-wood.com
Wed Jul 26 01:32:28 EDT 2006


I'm just starting out with Tkinter programming (using Programming
Python as a reference), and I couldn't find the answer to this
anywhere...

How do you catch general exceptions in a Tkinter program.  If you run
the below and click the "Exception" or "Callback Exception" buttons
you see a traceback on stderr under unix, and nothing at all under
windows (if run as a pyw).

How so you catch those exceptions so that they can pop up in a dialog?
There doesn't seem to be a hook. I was imagining that there would be a
global error handler I could hook / override?

from Tkinter import *

class AppDemo(Frame):
    """A sample tk app"""

    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.pack(expand=YES, fill=BOTH)
        self.make_tool_bar()
        self.master.title("A Title")
        self.bang = 0
        self.process()

    def process(self):
        self.after(1000, self.process)
        if self.bang:
            self.bang = 0
            raise ValueError("Callback Exception")
        
    def make_tool_bar(self):
        self.toolbar = Frame(self, cursor='hand2', relief=SUNKEN, bd=2)
        self.toolbar.pack(side=BOTTOM, fill=X)
        Button(self.toolbar, text='Exception', command=self.make_exception).pack(side=TOP, fill=X)
        Button(self.toolbar, text='Callback Exception', command=self.make_callback_exception).pack(side=TOP, fill=X)
        Button(self.toolbar, text='Quit', command=self.quit).pack(side=TOP, fill=X)

    def make_exception(self):
        raise ValueError("Exception")

    def make_callback_exception(self):
        self.bang = 1

if __name__ == "__main__":
    AppDemo().mainloop()

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list