Tkinter and exceptions
Peter Otten
__peter__ at web.de
Wed Jul 26 02:30:48 EDT 2006
Nick Craig-Wood wrote:
> 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?
Overriding report_callback_exception() seems to work:
> from Tkinter import *
import traceback
import tkMessageBox
>
> 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
def show_error(*args):
a = traceback.format_exception(*args)
tkMessageBox.showerror(a[-1], "\n".join(a[:-1]))
self._root().report_callback_exception = show_error
> 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()
Peter
More information about the Python-list
mailing list