【问题标题】:How to load multiple images in PyGame?如何在 PyGame 中加载多个图像?
【发布时间】: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。

标签: python pygame


【解决方案1】:

您确实通过调用load("tomato") 来加载图像,但您忽略了返回值。试试

tomato = load("tomato")

改为。

【讨论】:

  • 我保持原样使用该功能并使用这条线,并且它工作了 - 为 199 多个图像执行此操作比以前少了一点乏味,谢谢!
【解决方案2】:

如果要加载这么多图片,使用os.listdir 并将目录中的所有图片放入字典中。另外,在加载图片后使用convert 或convert_alpha 可以提高性能。

def load_images(path_to_directory):
    """Load images and return them as a dict."""
    image_dict = {}
    for filename in os.listdir(path_to_directory):
        if filename.endswith('.png'):
            path = os.path.join(path_to_directory, filename)
            key = filename[:-4]
            image_dict[key] = pygame.image.load(path).convert()
    return image_dict

如果您还想从子目录加载所有图像,请使用os.walk:

def load_images(path_to_directory):
    """Load all images from subdirectories and return them as a dict."""
    images = {}
    for dirpath, dirnames, filenames in os.walk(path_to_directory):
        for name in filenames:
            if name.endswith('.png'):
                key = name[:-4]
                img = pygame.image.load(os.path.join(dirpath, name)).convert()
                images[key] = img
    return images

【讨论】:

  • 如何从一个文件中的 7 个子文件中加载多个图像?
  • 你的意思是要加载7个子目录下的所有图片吗?然后你可以使用os.walk 或者使用我上面几次展示的函数(然后你会得到7个不同的字典)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
  • 2012-03-09
相关资源
最近更新 更多