Handling exception in python tkinter

后端 未结 4 631
刺人心
刺人心 2020-12-18 09:56

I have written an application in Python Tkinter. I recently noticed that for one of the operation, it sometimes closes (without giving any error) if that operation failed.

4条回答
  •  执念已碎
    2020-12-18 10:40

    You can override Tkinter's CallWrapper. It is necessary to use a named import of Tkinter instead of a wildcard import in order to do so:

    import Tkinter as tk
    import traceback
    
    class Catcher: 
        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('test.log', 'a'))
    
    # ...
    tk.CallWrapper = Catcher
    b = tk.Button(master, text="OK", command=copydir)
    b.pack()
    master.mainloop()
    

提交回复
热议问题