简体   繁体   English

为什么通用的“ try / except”块不适用于Python TkInter回调?

[英]Why does an generic “try / except” block not apply to a Python TkInter callback?

I have determined that in a Python TkInter GUI program, it is best practice to enclose the entire thing in a try / except block in order to catch all exceptions and present them to the end user (as opposed to something going wrong silently or the program exiting for seemingly no reason). 我已经确定,在Python TkInter GUI程序中,最佳做法是将整个内容封装在try / except块中,以便捕获所有异常并将其呈现给最终用户(而不是静默地出错或程序出错)似乎没有理由退出)。

However, this approach has some problems. 但是,这种方法存在一些问题。 Consider the following tiny program that attempts to divide by 0 when a button is clicked: 考虑下面的微型程序,当单击按钮时,该程序试图将其除以0:

import tkinter

class Foo():
    def __init__(self):
        # Initialize a new GUI window
        root = tkinter.Tk()

        # The "Generic error" message is shown when the following is uncommented
        #number = 1 / 0

        # Define a button and draw it
        button = tkinter.Button(root, text='Generate an error', command=self.generate_error)
        button.pack()

        # Loop forever
        root.mainloop()

    def generate_error(self):
        # The "Generic error" message is not shown
        number = 1 / 0



if __name__ == '__main__':
    try:
        # Run the Foo class
        Foo()

    except Exception as e:
        print('Generic error:', str(e))

Why does the "Generic error" statement not apply to the button callback function? 为什么“通用错误”语句不适用于按钮回调函数?

The following StackOverflow post was helpful: Should I make silent exceptions louder in tkinter? 以下StackOverflow帖子对您有所帮助: 我应该在tkinter中使静音异常更大声吗?

Basically, I need to use report_callback_exception . 基本上,我需要使用report_callback_exception I've modified the code snippet accordingly: 我已经相应地修改了代码片段:

import tkinter
import tkinter.messagebox
import traceback

class Foo():
    def __init__(self):
        # Initialize a new GUI window
        tkinter.Tk.report_callback_exception = callback_error  # TkInter callbacks run in different threads, so if we want to handle generic exceptions caused in a TkInter callback, we must define a specific custom exception handler for that
        root = tkinter.Tk()

        # The error() function is triggered when the following is uncommented
        #number = 1 / 0

        # Define a button and draw it
        button = tkinter.Button(root, text='Generate an error', command=self.generate_error)
        button.pack()

        # Loop forever
        root.mainloop()

    def generate_error(self):
        # The "callback_error()" function is triggered when the button is clicked
        number = 1 / 0


def error(message, exception):
    # Build the error message
    if exception is not None:
        message += '\n\n'
        message += traceback.format_exc()

    # Also log the error to a file
    # TODO

    # Show the error to the user
    tkinter.messagebox.showerror('Error', message)

    # Exit the program immediately
    exit()


def callback_error(self, *args):
    # Build the error message
    message = 'Generic error:\n\n'
    message += traceback.format_exc()

    # Also log the error to a file
    # TODO

    # Show the error to the user
    tkinter.messagebox.showerror('Error', message)

    # Exit the program immediately
    exit()



if __name__ == '__main__':
    try:
        # Run the Foo class
        Foo()

    except Exception as e:
        error('Generic error:', e)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM