用Tkin处理未捕获的异常

2024-04-25 06:39:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的Tkinter Python应用程序中,我试图使用sys.excepthook来处理未捕获的异常,但我的处理程序从未被调用。堆栈跟踪仍然打印出来。在

如何处理Tkinter应用程序中未捕获的异常?在

下面是一个简单的例子,展示了我的尝试:

import Tkinter as tk
import tkMessageBox
import traceback
import sys

class MyApp(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.button_frame = tk.Frame(self)
        self.button_frame.pack(side='top')
        self.button_run = tk.Button(
            self.button_frame, text="Run", command=self.run
        )
        self.button_run.grid(row=0, column=1, sticky='W')

    def run(self):
        tkMessageBox.showinfo('Info', 'The process is running.')
        raise RuntimeError('Tripped.')

def main():
    root = tk.Tk()  # parent widget

    MyApp(root).pack(fill='both', expand=True)

    def handle_exception(exc_type, exc_value, exc_traceback):
        message = ''.join(traceback.format_exception(exc_type,
                                                     exc_value,
                                                     exc_traceback))
        tkMessageBox.showerror('Error', message)

    sys.excepthook = handle_exception

    root.mainloop()  # enter Tk event loop

if __name__ == '__main__':
    main()

Tags: runimportselfmaintkinterdefsysbutton
1条回答
网友
1楼 · 发布于 2024-04-25 06:39:54

在引发异常之后,我逐步检查了代码,发现它被^{}捕获。经过进一步的搜索,我找到了一篇介绍如何override ^{}的帖子。下面是我的新处理程序示例。不要忘记__init__()中的第二行,在那里您实际注册了处理程序。在

import Tkinter as tk
import tkMessageBox
import traceback

class MyApp(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        parent.report_callback_exception = self.report_callback_exception
        self.parent = parent
        self.button_frame = tk.Frame(self)
        self.button_frame.pack(side='top')
        self.button_run = tk.Button(
            self.button_frame, text="Run", command=self.run
        )
        self.button_run.grid(row=0, column=1, sticky='W')

    def run(self):
        tkMessageBox.showinfo('Info', 'The process is running.')
        raise RuntimeError('Tripped.')

    def report_callback_exception(self, exc_type, exc_value, exc_traceback):
        message = ''.join(traceback.format_exception(exc_type,
                                                     exc_value,
                                                     exc_traceback))
        tkMessageBox.showerror('Error', message)

def main():
    root = tk.Tk()  # parent widget

    MyApp(root).pack(fill='both', expand=True)

    root.mainloop()  # enter Tk event loop

if __name__ == '__main__':
    main()

相关问题 更多 >