pygame渐变函数中的UnboundLocalError

时间:2016-03-25 01:15:44

标签: python scope

我试图使用此代码制作彩虹渐变,但我得到了UnboundLocalError

import pygame, random, time

Red = 0
Blue = 0
Green = 0

background_color = (Red, Green, Blue)
(width, height) = (300, 200)


def ChangeRa():
   Red += 1
def ChangeGa():
   Green += 1
def ChangeBa():
   Blue += 1
def ChangeRs():
   Red += 1
def ChangeGs():
   Green += 1
def ChangeBs():
   Blue += 1

while Red <= 255:
   ChangeRa()
   time.sleep(0.1)
while Green <= 255:
   ChangeGa()
   time.sleep(0.1)
while Blue <= 255:
   ChangeBa()
   time.sleep(0.1)
while Red >= 0:
   ChangeRs()
   time.sleep(0.1)
while Green >= 0:
   ChangeGs()
   time.sleep(0.1)
while Blue >= 0:
   ChangeBs()
   time.sleep(0.1)

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Rainbow!!!')
screen.fill(background_colour)

def close():
   running = True
   while running:
      for event in pygame.event.get():
         if event.type == pygame.QUIT:
            running = False
   pygame.quit()

close()

这是错误消息:

Traceback (most recent call last):
  File "/home/ronnochj/Fill.py", line 25, in <module>
    ChangeRa()
  File "/home/ronnochj/Fill.py", line 12, in ChangeRa
    Red += 1
UnboundLocalError: local variable 'Red' referenced before assignment

1 个答案:

答案 0 :(得分:0)

您在此处分配之前引用Red(同样适用于BlueGreen):

def ChangeRa():
    Red += 1

你可以这样说:

Red = 0
global Red

然后

def ChangeRa():
    Red += 1

请记住,外部Red仅在ChangeRa之外定义。如果希望在函数中可以访问全局变量,请使用全局变量。

TLDR : 在global Red, Blue, Green

后面的行中添加Green = 0