使用 Tkinter 处理未捕获的异常 [英] Handle uncaught exceptions with Tkinter

查看:29
本文介绍了使用 Tkinter 处理未捕获的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Tkinter Python application, I tried to use sys.excepthook to handle uncaught exceptions, but my handler was never called. The stack trace still printed out.

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

How can I handle uncaught exceptions in a Tkinter application?

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

Here's a trivial example that shows what I tried:

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()

推荐答案

我在引发异常后单步调试代码,发现它被 report_callback_exception().更多的搜索让我找到了一篇文章,展示了如何覆盖report_callback_exception().这是我使用新处理程序的示例.不要忘记 __init__() 中实际注册处理程序的第二行.

I stepped through the code after the exception is raised, and found that it gets caught by report_callback_exception(). Some more searching led me to a post that shows how to override report_callback_exception(). Here is my example with the new handler. Don't forget the second line in __init__() where you actually register the handler.

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()

这篇关于使用 Tkinter 处理未捕获的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆