为什么Python中的装饰风格上下文管理器不';t在Tkinter窗口内捕获异常?
有一个简单的代码,其中包含通过contextlib由decorator生成的上下文管理器。当我按下按钮时,引发异常,上下文管理器不处理异常。为什么为什么Python中的装饰风格上下文管理器不';t在Tkinter窗口内捕获异常?,python,exception-handling,tkinter,Python,Exception Handling,Tkinter,有一个简单的代码,其中包含通过contextlib由decorator生成的上下文管理器。当我按下按钮时,引发异常,上下文管理器不处理异常。为什么 from Tkinter import Tk, Button from contextlib import contextmanager def close_window(): window.destroy() raise Exception @contextmanager def safe(): try:
from Tkinter import Tk, Button
from contextlib import contextmanager
def close_window():
window.destroy()
raise Exception
@contextmanager
def safe():
try:
yield
except:
print 'Exception catched'
with safe():
window = Tk()
button = Button(window, text='Press me', command=close_window)
button.pack()
window.mainloop()
为什么例外仍然会出现
UPD我使用Python2.7Tkinter主进程循环不会因异常而停止,也不会进一步传播它们。因此,异常永远不会到达
with
语句(因为tkinter本身捕获并报告异常,然后停止执行)
您需要创建一个decorator来捕获这些异常并记录它们,或者执行您想要执行的任何逻辑
范例-
from Tkinter import Tk, Button
from contextlib import contextmanager
class exceptioncatcher: # <---the decorator
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
try:
return self.function(*args, **kwargs)
except Exception:
print 'Exception catched1'
@exceptioncatcher
def close_window():
window.destroy()
raise Exception
@contextmanager
def safe():
try:
yield
except Exception:
print 'Exception catched'
with safe():
window = Tk()
button = Button(window, text='Press me', command=close_window)
button.pack()
window.mainloop()
从Tkinter导入Tk,按钮
从contextlib导入contextmanager
class exceptioncatcher:#“safe”是一个有点误导性的名字,它是一个基本的名称。它不会重现在我看来,它是在Python 3中发现的。4@AnandSKumar,我使用Python 2.7def\uu调用(self,*args,**kwargs):尝试:返回self.function(*args,**kwargs).
@AnandSKumar非常感谢!这就是我对Tkinter windows所不知道的。@WalkingBe摆欢迎:),很高兴它帮助了你。