在使用try和except语句赋值之前引用的局部变量

Tha*_*ame 7 python try-catch

我在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'
Run Code Online (Sandbox Code Playgroud)

所以我想用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 = ''
Run Code Online (Sandbox Code Playgroud)

新的错误消息:

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
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么会发生这种情况以及如何解决它所以任何帮助将不胜感激.

提前致谢.

ale*_*cxe 7

如果try/except块中存在异常,则不会在范围中定义entryx和entryy变量.

你应该抛出并抛出错误并退出程序或在块中分配entryx和entryy默认值except.

此外,您可以进行while循环,直到用户输入像此处建议的整数.


KGo*_*KGo 5

要添加到@ alecxe的答案,我宁愿修改程序,如下所示:

    entryx, entryy = 0, 0
    try:
        entryx = int(e1.get())
        entryy = int(e2.get())
    except ValueError:
        print("text")
Run Code Online (Sandbox Code Playgroud)

基本上,错误的含义是,如果出现错误,entryx, entryy永远不会分配任何内容,但仍会在if..else检查中稍后引用.

最好为try..except块外部的变量设置默认值.