如何修复Python中的“名称未定义”错误

时间:2019-01-08 18:50:18

标签: python

我没有定义错误名称,它显示如下:-

  

回溯(最近一次通话最后一次):文件“ C:/ Users / Shashank Kumar / AppData / Local / Programs / Python / Python37 / ssss.py”,行1084,位于changeBackgroundAnimation中       DISPLAYSURF.fill(bgcolor)   NameError:未定义名称“ bgcolor”

def changeBackgroundAnimation(animationSpeed=40):
    global bgcolor
    newBgColor=(random.randint(0,255),random.randint(0,255),random.randint(0,255))
    newBgSurf=pygame.Surface((WINDOWWIDTH,WINDOWHEIGHT))
    newBgSurf=newBgSurf.convert_alpha()
    r,g,b=newBgColor
    for alpha in range(0,255,animationSpeed):
        checkForQuit()
        DISPLAYSURF.fill(bgcolor)
        newBgSurf.fill((r,g,b,alpha))
        DISPLAYSURF.blit(newBgSurf,(0,0))
        drawButtons()
        pygame.display.update()
        FPSCLOCK.tick(FPS)
    bgcolor=newBgColor
  

NameError:名称'bgcolor'未定义

1 个答案:

答案 0 :(得分:1)

global bgcolor未定义,声明或创建变量。它只是声明应使用该名称的全局变量,而不是局部变量。您仍然需要确保在DISPLAYSURF.fill(bgcolor)中首次使用它之前就已对其进行了定义。具体来说,您需要在首次调用changeBackgroundAnimation之前为变量分配一个值。

相关问题