Handling exception in python tkinter

后端 未结 4 635
刺人心
刺人心 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:21

    I am not very sure if I have understood you well, but this simple code gives you control over the case in which the directory could not be found:

    import os
    from Tkinter import *
    
    def copydir():
        src = "D:\\troll"
        dest = "D:\\trollo"
    
        try:
            os.rename(src, dest)
        except:
            print 'Sorry, I couldnt rename'
            # optionally: raise YourCustomException
            # or use a Tkinter popup to let the user know
    
    master = Tk()
    
    b = Button(master, text="OK", command=copydir)
    b.pack()
    
    mainloop()
    

    EDIT: Since you want a general method and Tkinter does not propagate exceptions, you have to program it. There are two ways:

    1) Hardcode it into the the functions as I did in the example above (horrible)

    2) Use a decorator to add a try-except block.

    import os
    from Tkinter import *
    
    
    class ProvideException(object):
        def __init__(self, func):
            self._func = func
    
        def __call__(self, *args):
    
            try:
                return self._func(*args)
    
            except Exception, e:
                print 'Exception was thrown', str(e)
                # Optionally raise your own exceptions, popups etc
    
    
    @ProvideException
    def copydir():
        src = "D:\\troll"
        dest = "D:\\trollo"
    
        os.rename(src, dest)
    
    master = Tk()
    
    b = Button(master, text="OK", command=copydir)
    b.pack()
    
    mainloop()
    

    EDIT: If you want to include the stack

    include traceback
    

    and in the except block:

    except Exception, e:
        print 'Exception was thrown', str(e)
        print traceback.print_stack()
    

    The solution that A.Rodas has proposed is cleaner and more complete, however, more complicated to understand.

提交回复
热议问题