我为使用 Tkinter 接收用户输入的其他人开发了几个 Python 程序。为了保持简单和用户友好,命令行或 python 控制台从不出现(即使用 .pyw 文件),所以我正在研究使用日志库将错误文本写入文件时发生异常。但是,我很难让它真正捕获异常。例如:
我们编写了一个会导致错误的函数:
def cause_an_error():
a = 3/0
Run Code Online (Sandbox Code Playgroud)
现在我们尝试正常记录错误:
import logging
logging.basicConfig(filename='errors.log', level=logging.ERROR)
try:
cause_an_error()
except:
logging.exception('simple-exception')
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,程序出错,日志记录将错误写入 errors.log。控制台中什么也没有出现。但是,当我们实现 Tkinter 接口时,会有不同的结果,如下所示:
import logging
import Tkinter
logging.basicConfig(filename='errors.log', level=logging.ERROR)
try:
root = Tkinter.Tk()
Tkinter.Button(root, text='Test', command=cause_an_error).pack()
root.mainloop()
except:
logging.exception('simple-exception')
Run Code Online (Sandbox Code Playgroud)
在这种情况下,按下 Tkinter 窗口中的按钮会导致错误。但是,这一次,没有写入文件,控制台中出现以下错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "C:/Users/samk/Documents/GitHub/sandbox/sandbox2.pyw", line 8, in cause_an_error
a = 3/0
ZeroDivisionError: integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)
有没有不同的方法来捕捉和记录这个错误?
它没有很好的文档记录,但是 tkinter 调用了一个方法来处理由于回调而发生的异常。您可以通过report_callback_exception在根窗口上设置属性来编写自己的方法来做任何您想做的事情。
例如:
import tkinter as tk
def handle_exception(exception, value, traceback):
print("Caught exception:", exception)
def raise_error():
raise Exception("Sad trombone!")
root = tk.Tk()
# setup custom exception handling
root.report_callback_exception=handle_exception
# create button that causes exception
b = tk.Button(root, text="Generate Exception", command=raise_error)
b.pack(padx=20, pady=20)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
以供参考: