簡體   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