Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x &引用;UnboundLocalError:局部变量';播放按钮';作业前参考“;当我移除我的演员时发生了什么_Python 3.x_Pygame - Fatal编程技术网

Python 3.x &引用;UnboundLocalError:局部变量';播放按钮';作业前参考“;当我移除我的演员时发生了什么

Python 3.x &引用;UnboundLocalError:局部变量';播放按钮';作业前参考“;当我移除我的演员时发生了什么,python-3.x,pygame,Python 3.x,Pygame,当我用值“None”或其他任何东西替换我的actor时,会出现以下错误: UnboundLocalError:分配前引用的局部变量“playbutton” 我在碰撞点上的代码如下: if playbutton.collidepoint(pos): playbuttonpressed = True print('Play button has been pressed') playbutton = None screen.fi

当我用值“None”或其他任何东西替换我的actor时,会出现以下错误:

UnboundLocalError:分配前引用的局部变量“playbutton”

我在碰撞点上的代码如下:

    if playbutton.collidepoint(pos):
        playbuttonpressed = True
        print('Play button has been pressed')
        playbutton = None
        screen.fill((143, 188, 143))
        pygame.display.update()
        wait(1)
    else:
        print('Play button has not been pressed')

由于is
playbutton
是全局命名空间中的一个变量,因此导致该错误。如果删除
playbutton=None
,则
playbutton.collidepoint(pos)
使用全局命名空间中的变量,因为该变量是读取的(读取访问权限),并且不会出现错误

只要添加表达式
playbutton=None
playbutton
就是函数局部范围内的变量<代码>播放按钮。collidepoint(pos)希望访问本地范围内的变量。由于局部变量未在出现错误时赋值

UnboundLocalError:分配前引用的局部变量“playbutton”

注意,编译器将
playbutton
识别为局部变量,因为赋值
playbutton=None
(在代码实际执行之前),但局部变量
playbutton
未在
playbutton.collidatepoint(pos)
处赋值
另见


当分配了
playbutton
并且更改了全局变量而不是局部变量时,使用来指示它是一个全局变量:

def your_function():
    # [...]

    global playbutton 

    if playbutton.collidepoint(pos):
        playbuttonpressed = True
        print('Play button has been pressed')
        playbutton = None
        # [...]

但我会设法解决的