如何在tkinter中大声让无声例外? [英] How can I make silent exceptions louder in tkinter?

查看:105
本文介绍了如何在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提到了可能性不同的异常报告功能的区别nt帧。我还没看到怎么做。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆