tkinter python:捕捉异常 [英] tkinter python: catching exceptions

查看:214
本文介绍了tkinter python:捕捉异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从python开始编程我觉得在家里有错误报告。现在我正在使用Tkinter进行编程,我发现经常发生的是,我的程序中有错误,即使它们产生异常,我也没有注意到:我抓住它们(有时)只是因为我去调试步骤Step(我使用wingIDE),例如在给定的行我看到异常报告。但是令我感到烦恼的是程序不会停止,但是即使在不是里面的try / error中也会发生这种情况。

Starting to program in python I felt at home with its error reporting. Now that I'm programming with Tkinter instead, I'm finding that it often happens that there are errors in my program that I do not notice even if they generate an exception: I catch them (sometimes) just because I go debugging Step by Step (I use wingIDE) and e.g. at a given line I see the exception reported. But what annoys me is that the program doesn't stop, yet this happens even in blocks not inside try/error.

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

If what I said makes any sense, do you know about some overall approach to at least display the errors? Being in Tkinter I could create an error window, and fill it with any exception is being generated, when it happens.

推荐答案

Tkinter主进程循环不会被异常所导致,也不会进一步传播。您的代码必须捕获所有异常。一个简单的方法是使用装饰器:

The Tkinter main process loop is not brought down by exceptions and does not propagate them further. Your code must catch all exceptions. An easy way to do this is to use a decorator:

from Tkinter import *

class safe: # the decorator
  def __init__(self, function):
    self.function = function

  def __call__(self, *args):
    try:
      return self.function(*args)
    except Exception, e:
      # make a popup here with your exception information.
      # might want to use traceback module to parse the exception info
      print "Error: %s" % (e)

@safe
def bad():
    1/0

root = Tk()
b = Button(root, text="press me", command=bad)
b.pack()

这篇关于tkinter python:捕捉异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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