我在 try 和 except 语句中遇到了一些问题,我有一个输入小部件,它接受字符串中的输入,但我有稍后将其转换为整数的代码,问题是如果用户输入类似文本的内容,它会引发这样的错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.2/tkinter/__init__.py", line 1402, in __call__
return self.func(*args)
File "/home/ppppwn3d/workspace/Python/JailBreakBob/JailBreakBob.py", line 157, in buttonclick_gamescreen
entryx = int(e1.get())
ValueError: invalid literal for int() with base 10: 'abc'
所以我想用 try 和 except 语句隐藏错误,但我现在收到另一条错误消息。
这就是它在代码中的样子。
while pressed == 8 :
try:
entryx = int(e1.get())
entryy = int(e2.get())
except ValueError:
print("text")
answerx = answerlistx[randomimage]
answery = answerlisty[randomimage]
if entryx == answerx and entryy == answery
canvas.delete(images)
randomimage = random.randrange(0,49+1)
scorecounter = scorecounter + 1
game = PhotoImage(file=imagelist[randomimage])
images = canvas.create_image(30, 65, image = game, anchor = NW)
e1.delete(0, END)
e2.delete(0, END)
pressed = ''
if entryx > 10 or entryx < -10 or entryy > 10 or entryy < -10 :
wrong = canvas.create_image(30, 65, image = outside, anchor = NW)
e1.delete(0, END)
e2.delete(0, END)
pressed = ''
else:
wrong = canvas.create_image(30, 65, image = incorrect, anchor = NW)
e1.delete(0, END)
e2.delete(0, END)
pressed = ''
新的错误信息:
text
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.2/tkinter/__init__.py", line 1402, in __call__
return self.func(*args)
File "/home/ppppwn3d/workspace/Python/JailBreakBob/JailBreakBob.py", line 165, in buttonclick_gamescreen
if entryx == answerx and entryy == answery:
UnboundLocalError: local variable 'entryx' referenced before assignment
我无法弄清楚为什么会发生这种情况以及如何解决它,因此我们将不胜感激。