【发布时间】:2017-05-02 07:33:45
【问题描述】:
我需要在 pygame 中加载大约 200 张图像,以便在我的游戏中的不同点进行 blitted。我尝试为此编写一个函数,但不断返回NameError: name 'tomato' is not defined。
所有图片名称都是加载图片的变量存放在下面:tomato = pygame.image.load("tomato.png")
使用数组会更好,如果可以,我该怎么做?
代码:
def load(image):
imagename = image
imagetitle = str(imagename)+".png"
image = pygame.image.load(imagetitle)
return image
load("tomato")
def blit_f(fruit):
gamedisplay.blit(fruit,(0,0))
pygame.display.update()
fruitlist = []
running = False
while not running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = True
if event.type == pygame.MOUSEMOTION:
mouse = pygame.mouse.get_pos()
color = screen.get_at(mouse)
if color == (209,0,0,255):
blit_f(tomato)
fruitlist.insert(0,"tomato")
if event.type == pygame.MOUSEBUTTONDOWN:
if fruitlist[0] == "tomato":
gamedisplay.blit(tomato,(0,0))
pygame.display.update()
NameError 仅在满足导致tomato.png blitting 的条件时发生:当我将鼠标悬停在番茄图像上时,即红色
如果我写load(tomato) 而不是"",那么我一运行代码就会出现NameError,并像load("tomato") 一样突出显示load(tomato) 而不是gamedisplay.blit(tomato)。
【问题讨论】:
-
您的代码在哪里显示您在定义番茄之前尝试使用它?
-
检查代码中的操作顺序
-
使用导致此错误的代码编辑您的原始问题@I.Kaur
-
函数有参数 load(image) 和 load(tomato) 在函数后面。该错误突出显示了后面的一行:gamedisplay.blit(tomato)
-
显示您的代码的全部,问题是在您调用
load(tomato)时未定义tomato。