2011-07-12 70 views
4

开始在Python中编程我觉得在家里有错误报告。现在我正在用Tkinter编程,我发现它经常发生我的程序中有错误,即使它们产生了一个异常我也没有注意到:我赶上它们(有时)只是因为我去调试Step by步骤(我使用wingIDE)和例如在给定的行我看到异常报告。但令我恼火的是,程序不会停止,但即使在而不是内部的try/error中也会发生这种情况。tkinter python:捕捉异常

如果我说的是有道理的,你知道一些总体方法来至少显示错误吗?在Tkinter中,我可以创建一个错误窗口,并在发生异常时填充它。

+2

有一个优雅的解决方案:http://stackoverflow.com/questions/4770993/silent-exceptions- in-python-tkinter-should-i-make-them-louder-how – Gonzo

+0

[我应该在tkinter中声明无声的例外吗?](https://stackoverflow.com/questions/4770993/should-i-make -silent-exceptions-louder-in-tkinter) –

回答

7

请参阅How can I make silent exceptions louder in tkinter的回答,其中显示如何将回调挂钩到tkinter.Tk.report_callback_exception

+0

感谢你的帮助,我可以_或多或少地让它工作。但我并不熟悉@safe语法(新手python程序员),所以我不知道在哪里把它放在我的代码中......在我看来,我必须在每个函数定义之前放置@safe被观看......是这样吗? – alessandro

+0

@alessandro:你是对的。这些被称为装饰者。装饰器是调用可以包装其他函数的类和函数的语法糖。 –

+0

@StevenRumbalski我故意不改变进口。我只做了与Python 2向后兼容的编辑。 –

5

正如@约亨 - ritzel说(Should I make silent exceptions louder in 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