开始使用Python编程时,我发现其错误报告非常容易理解。然而,现在我用Tkinter编程时,有时候即使出现异常错误,我也注意不到我的程序中存在错误:有时我只是因为要逐步调试(我使用wingIDE)而捕获它们,并在给定行处看到异常报告。但是让我困扰的是,程序并没有停止,这种情况甚至发生在未包含try/error块内部。
如果我说的有意义,你是否知道一些整体方法来至少显示错误?在Tkinter中,我可以创建一个错误窗口,并在发生异常时将其填充到其中。
开始使用Python编程时,我发现其错误报告非常容易理解。然而,现在我用Tkinter编程时,有时候即使出现异常错误,我也注意不到我的程序中存在错误:有时我只是因为要逐步调试(我使用wingIDE)而捕获它们,并在给定行处看到异常报告。但是让我困扰的是,程序并没有停止,这种情况甚至发生在未包含try/error块内部。
如果我说的有意义,你是否知道一些整体方法来至少显示错误?在Tkinter中,我可以创建一个错误窗口,并在发生异常时将其填充到其中。
查看如何使tkinter中的静默异常更加明显的答案,这些答案展示了如何将回调函数挂钩到tkinter.Tk.report_callback_exception
中。
future import
时,print 3
和print(3)
是相同的,但print 1, 2, 3
和print(1, 2, 3)
的输出分别为1 2 3
和(1, 2, 3)
。而执行print(1, end='')
会出现语法错误。单个参数没有问题,因为括号可以被忽略。多个参数变成元组,因为逗号。我认为命名参数是一个问题,因为Python已经决定print
是一个语句,所以它甚至不会尝试将其视为函数。 - Steven Rumbalski正如@jochen-ritzel所说(Python 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小部件,它主要代表应用程序的主窗口,而不是注入一个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()
在我看来,这似乎是正确的方式。