Thursday 26 September 2013

Python tkinter exception handling using tkinter callwrapper

Python tkinter exception handling using tkinter callwrapper

I want to catch all the exceptions from tkinter application and dump them
in a text file. I am using tkinter callwrapper method for the same but it
doesn't seems to work.
In the belowcode NameError exception is there, but when I launch the
application by double clicking on the program, it just closes without
dumping/giving the error in tkmessagebox.
import Tkinter as tk
import tkMessageBox
class GUIExceptionHandler:
def __init__(self, func, subst, widget):
self.func = func
self.subst = subst
self.widget = widget
def __call__(self, *args):
try:
if self.subst:
args = apply(self.subst, args)
return apply(self.func, args)
except SystemExit, msg:
raise SystemExit, msg
except:
traceback.print_exc(file=open('stacktrace.log', 'w'))
tkMessageBox.showerror("TestApp", "Encountered an error.")
#root.quit()
class GUI:
def __init__(self):
self.root = None
self.__createMainWindow()
self.__GUImainloop()
def __closeApp(self):
if tkMessageBox.askyesno("Yes", "Do you really want to exit?"):
self.root.destroy()
def __createMainWindow(self):
self.root = tk.Tk()
self.root.withdraw()
tk.CallWrapper = GUIExceptionHandler
self.root.protocol("WM_DELETE_WINDOW",self.__closeApp)
errorcondition #NameSpaceError condition
def __GUImainloop(self):
self.root.mainloop()
def main():
gui = GUI()
if __name__ == '__main__':
main()
Can someone please suggest what is wrong in this code and how this can be
achieved?

No comments:

Post a Comment