Python 3.x &引用;UnboundLocalError:局部变量';播放按钮';作业前参考“;当我移除我的演员时发生了什么
当我用值“None”或其他任何东西替换我的actor时,会出现以下错误: UnboundLocalError:分配前引用的局部变量“playbutton” 我在碰撞点上的代码如下: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
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
# [...]
但我会设法解决的