tkinter Python: 捕获异常

10 投票
3 回答
20020 浏览
提问于 2025-04-16 21:21

刚开始学习Python编程的时候,我觉得它的错误报告很友好。但现在我在用Tkinter编程时,发现程序里常常会出现错误,我却没注意到,即使这些错误会产生异常。我有时候只有在逐步调试的时候(我用的是wingIDE)才会发现这些异常,比如在某一行代码时看到错误报告。但让我感到烦恼的是,程序并没有停止运行,甚至在那些不在try/except块里的代码中也会出现这种情况。

如果我说的这些有道理的话,你知道有没有什么方法可以整体上显示这些错误吗?在Tkinter中,我可以创建一个错误窗口,把所有产生的异常都显示在里面,这样就能及时看到错误了。

3 个回答

1

我更喜欢直接扩展Tk的顶层窗口小部件,因为它主要代表了应用程序的主窗口,而不是用一些小技巧来实现:

import tkinter as tk
from tkinter import messagebox

class FaultTolerantTk(tk.Tk):
    def report_callback_exception(self, exc, val, tb):
        self.destroy_unmapped_children(self)
        messagebox.showerror('Error!', val)

    # NOTE: It's an optional method. Add one if you have multiple windows to open
    def destroy_unmapped_children(self, parent):
        """
        Destroys unmapped windows (empty gray ones which got an error during initialization)
        recursively from bottom (root window) to top (last opened window).
        """
        children = parent.children.copy()
        for index, child in children.items():
            if not child.winfo_ismapped():
                parent.children.pop(index).destroy()
            else:
                self.destroy_unmapped_children(child)

def main():
    root = FaultTolerantTk()
    ...
    root.mainloop()


if __name__ == '__main__':
    main()

在我看来,这样做是正确的方式。

9

正如 @jochen-ritzel 所说(在 tkinter 中,我应该让静默异常更明显吗?),你可以重写 tk.TK.report_callback_exception() 这个方法:

import traceback
import tkMessageBox

# You would normally put that on the App class
def show_error(self, *args):
    err = traceback.format_exception(*args)
    tkMessageBox.showerror('Exception',err)
# but this works too
tk.Tk.report_callback_exception = show_error
9

可以查看这个链接的回答:如何让tkinter中的静默异常变得更明显,里面展示了如何将一个回调函数连接到 tkinter.Tk.report_callback_exception

撰写回答