2016-03-25 92 views
0

我試圖用這段代碼做一個彩虹漸變,但是我得到了一個UnboundLocalErrorpygame漸變函數中的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

你在這裏工作之前引用Red(同樣適用於BlueGreen):

def ChangeRa(): 
    Red += 1 

你可以這樣說: :

Red = 0 
global Red 

然後

def ChangeRa(): 
    Red += 1 

記住外Red只ChangeRa之外定義。如果您希望在函數中可以訪問全局變量,請使用全局變量。

TLDR: 添加就行global Red, Blue, Green以下Green = 0