我的示例代码:
from tkinter import *
class first:
def __init__(self):
self.top = Tk()
...
def test(self):
try:
self.value = self.dict[key]
except KeyError:
try:
second()
except ValueError:
print('Finally')
class second:
def __init__(self):
self.frame = Toplevel()
...
self.button = ttk.Button(parent=self.frame, text='GO', command=self.go_click)
...
def go_click(self):
raise ValueError('Not Valid')
这只是一个例子!问题是ValueError是由第二个类引发的,但它不是由第一个类的except子句处理的。回溯下方:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "........", line xxx, in goclick
raise ValueError('Not Valid')
ValueError: Not Valid
我该如何妥善处理?
谢谢,
答案 0 :(得分:-1)
试试这个
from tkinter import *
class first:
def __init__(self):
self.top = Tk()
...
def test(self):
try:
self.value = self.dict[key]
except KeyError:
try:
second()
except ValueError:
print('Finally')
print "OK CALLED SECOND()!!!!" #######THIS PRINT MEANS YOUR DONE HERE
class second:
def __init__(self):
self.frame = Toplevel()
...
self.button = ttk.Button(parent=self.frame, text='GO', command=self.go_click)
...
def go_click(self):
raise ValueError('Not Valid')
为了实际处理该错误,您需要覆盖tkinters事件循环...不是很容易(或一般的好习惯)
更好的方法是处理go_click
函数中的错误本身就像
def go_click(self):
try:
self.submit_form()
except ValueError:
print "VALIDATION ERROR!!"