如何在 tkinter 中使无声异常更响亮? [英] How can I make silent exceptions louder in tkinter?
问题描述
如果我从终端运行以下代码,我会在终端中收到有用的错误消息:
If I run the following code from a terminal, I get a helpful error message in the terminal:
import Tkinter as tk
master = tk.Tk()
def callback():
raise UserWarning("Exception!")
b = tk.Button(master, text="This will raise an exception", command=callback)
b.pack()
tk.mainloop()
但是,如果我在没有终端的情况下运行它(例如,通过双击图标),则会抑制错误消息.
However, if I run it without a terminal (say, by double-clicking an icon), the error message is suppressed.
在我真实的、更复杂的 Tkinter 应用程序中,我喜欢 GUI 有点抗崩溃.我不喜欢我的用户很难给我有用的反馈来修复由此产生的意外行为.
In my real, more complicated Tkinter application, I like that the GUI is a little crash-resistant. I don't like that my users have a hard time giving me useful feedback to fix the resulting unexpected behavior.
我该如何处理?在 Tkinter 应用程序中是否有标准方法来公开回溯或 stderror 或诸如此类的东西?我正在寻找比将 try/except 放在任何地方更优雅的东西.
How should I handle this? Is there a standard way to expose tracebacks or stderror or whatnot in a Tkinter application? I'm looking for something more elegant than putting try/except everywhere.
Jochen Ritzel 在下面给出了一个很好的答案,它弹出了一个警告框,并提到将它附加到一个类中.只是为了明确这一点:
Jochen Ritzel gave an excellent answer below that pops up a warning box, and mentioned attaching it to a class. Just to make this explicit:
import Tkinter as tk
import traceback, tkMessageBox
class App:
def __init__(self, master):
master.report_callback_exception = self.report_callback_exception
self.frame = tk.Frame(master)
self.frame.pack()
b = tk.Button(
self.frame, text="This will cause an exception",
command=self.cause_exception)
b.pack()
def cause_exception(self):
a = []
a.a = 0 #A traceback makes this easy to catch and fix
def report_callback_exception(self, *args):
err = traceback.format_exception(*args)
tkMessageBox.showerror('Exception', err)
root = tk.Tk()
app = App(root)
root.mainloop()
我剩下的困惑:Jochen 提到了在不同的框架中有不同的异常报告功能的可能性.我还不知道如何做到这一点.这很明显吗?
My remaining confusion: Jochen mentions the possibility of having different exception reporting functions in different frames. I don't yet see how to do that. Is this obvious?
推荐答案
有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
如果你没有导入'Tkinter as tk',那么做
If you didn't import 'Tkinter as tk', then do
Tkinter.Tk.report_callback_exception = show_error
这篇关于如何在 tkinter 中使无声异常更响亮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!