我试图使用此代码制作彩虹渐变,但我得到了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
答案 0 :(得分:0)
您在此处分配之前引用Red
(同样适用于Blue
和Green
):
def ChangeRa():
Red += 1
你可以这样说:
Red = 0
global Red
然后
def ChangeRa():
Red += 1
请记住,外部Red
仅在ChangeRa之外定义。如果希望在函数中可以访问全局变量,请使用全局变量。
TLDR :
在global Red, Blue, Green
Green = 0