python NameError:全局名称

时间:2016-12-01 07:15:17

标签: python function pygame

您好我在尝试运行该函数时一直收到此错误,并且 在这种情况下选择一种颜色,它是粉红色的。

import pygame

导入系统 导入菜单 import rgbcolors 来自pygame.locals import * 来自rgbcolors import rgbcolor

def main():

# start screen
pygame.init()
screen1 = pygame.display.set_mode((500, 400))

# Fill background
background = pygame.Surface(screen1.get_size())
pygame.draw.line(screen1, (255, 0, 0), (230, 230), (100, 211), 4)
background = background.convert()
background.fill((0, 0,0))


# Displaying text
font = pygame.font.Font(None, 36)
text = font.render("Alien", 23, ((rgbcolor(pink))))
textpos = text.get_rect()
textpos.centerx = background.get_rect().centerx
background.blit(text, textpos)

screen1.blit(background, (0, 0))
pygame.display.flip()

while 1:
    for event in pygame.event.get():
        if event.type == QUIT:
            return
    screen1.blit(background, (0, 0))
    pygame.display.flip()
    pygame.time.get_ticks()

if __name__ == "__main__":
    main()

这是我的rgbcolor函数。

def rgbcolor(color):
    red = (255, 0, 0)
    green = (0, 255, 0)
    blue = (0, 0, 255)
    darkBlue = (0, 0, 128)
    white = (255, 255, 255)
    black = (0, 0, 0)
    pink = (255, 200, 200)

pass

错误代码。

    C:\Python27\python.exe C:/Users/Peter/PycharmProjects/game1/game.py
Traceback (most recent call last):
  File "C:/Users/Peter/PycharmProjects/game1/game.py", line 44, in <module>
    main()
  File "C:/Users/Peter/PycharmProjects/game1/game.py", line 27, in main
    text = font.render("Alien", 23, ((rgbcolor(pink))))
NameError: global name 'pink' is not defined

Process finished with exit code 1

1 个答案:

答案 0 :(得分:-2)

试试这个:

import pygame
from pygame.locals import *


def rgbcolor(color):
    colors = {'red': (255, 0, 0), 'green': (0, 255, 0), 'blue': (0, 0, 255),
              'darkBlue': (0, 0, 128), 'white': (255, 255, 255), 'black': (0, 0, 0),
              'pink': (255, 200, 200)}
    return colors[color]


def main():
    # start screen
    pygame.init()
    screen1 = pygame.display.set_mode((500, 400))

    # Fill background
    background = pygame.Surface(screen1.get_size())
    pygame.draw.line(screen1, (255, 0, 0), (230, 230), (100, 211), 4)
    background = background.convert()
    background.fill((0, 0, 0))

    # Displaying text
    font = pygame.font.Font(None, 36)
    text = font.render("Alien", 23, rgbcolor('pink'))
    textpos = text.get_rect()
    textpos.centerx = background.get_rect().centerx
    background.blit(text, textpos)
    screen1.blit(background, (0, 0))
    pygame.display.flip()
    while 1:
        for event in pygame.event.get():
            if event.type == QUIT:
                return
        screen1.blit(background, (0, 0))
        pygame.display.flip()
        pygame.time.get_ticks()


if __name__ == "__main__":
    main()