创建对pygame的图书馆并且我的全局变量无法工作

2024-10-01 07:24:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图制作一个简单的库来简化某些pygame函数和其他东西。当我尝试使用设置RGB变量的函数时,它说它没有定义

错误:

Traceback (most recent call last):
  File "C:\Users\matthew.shapiro\Desktop\Files_for_code_S2\librarytest.py", line 7, in <module>
    fill(BLACK)
NameError: name 'BLACK' is not defined
#library
import pygame
import math
def autoscreen(a,b):
    global size
    global screen
    size = (500,500)
    screen = pygame.display.set_mode(size)
def basicRGB():
    global BLACK
    BLACK = (   0,   0,   0)
    global WHITE
    WHITE = ( 255, 255, 255)
    global GREEN
    GREEN = (   0, 255,   0)
    global RED
    RED = ( 255,   0,   0)
    global BLUE
    BLUE = (   0,   0, 255)
def setPI():
    global PI
    PI = 3.141592653
def flip():
    pygame.display.flip()
def fps(c):
    global clock
    clock = pygame.time.Clock()
    clock.tick(c)
def fill(e):
    screen.fill(e)


#librarytest
import pygame
from easypygame import*
autoscreen(500,500)
fps(60)
flip()
basicRGB()
fill(BLACK)





Tags: 函数importsizedefdisplayfillscreenglobal
2条回答

如果这是在类中,而不是全局,请使用self.BLACK。如果不是,请使用字典,例如:

def basicRGB():
    dictionary={}
    dictionary.update({'BLACK':(   0,   0,   0)})
    return dictionary

def fill(dictionary, e):
    screen.fill(dictionary[e])

例如,转到this repl.it program that I made using this.

我建议导入稍微不同的内容,而不是使用from easypygame import*行,而是使用:import easypygame as ep或其他内容。Python中的全局变量实际上只是模块范围的变量,这就是为什么会出现错误,因为librarytest文件中没有BLACK。通过导入这种新方法,您可以使用:ep.BLACK从模块外部访问新模块的各个部分。这将允许您继续从内部pyeasygame更新变量,并从外部访问它们

相关问题 更多 >