繁体   English   中英

tkinter python:捕获异常

[英]tkinter python: catching exceptions

开始在 python 中编程我对它的错误报告感到宾至如归。 现在我正在使用 Tkinter 进行编程,我发现我的程序中经常出现错误,即使它们产生异常我也不会注意到:我捕获它们(有时)只是因为我 go 调试步骤步骤(我使用wingIDE),例如在给定的行中,我看到报告的异常。 但让我烦恼的是程序并没有停止,但即使在不在try/error 内的块中也会发生这种情况。

如果我所说的有任何意义,您是否知道一些至少显示错误的整体方法? 在 Tkinter 中,我可能会创建一个错误 window,并在发生任何异常时填充它。

请参阅如何在 tkinter 中使静默异常更响亮的答案,其中显示了如何将回调挂钩到tkinter.Tk.report_callback_exception

正如@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

我更喜欢显式扩展 Tk 的 Toplevel 小部件,它主要代表应用程序的主要 window 而不是注入 hack:

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

恕我直言,这看起来是正确的方法。

暂无
暂无

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

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