首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在PyGame中加载多个图像?

如何在PyGame中加载多个图像?
EN

Stack Overflow用户
提问于 2017-05-02 15:33:46
回答 2查看 3.7K关注 0票数 0

我需要在pygame中加载大约200个图像,以便在我的游戏中的不同点进行blitted。我试着为此编写了一个函数,但总是返回NameError: name 'tomato' is not defined

所有图像名称都是已加载图像的变量存储在下面的名称:tomato = pygame.image.load("tomato.png")

使用数组会更好吗?如果是的话,我该怎么做呢?

代码:

代码语言:javascript
复制
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的闪光

如果我编写load(tomato)而不是"",那么只要我运行代码,NameError就会出现,并突出显示load(tomato)而不是gamedisplay.blit(tomato),就像使用load("tomato")一样。

EN

回答 2

Stack Overflow用户

发布于 2017-05-02 16:35:13

您可以通过调用load("tomato")加载图像,但忽略返回值。试一试

代码语言:javascript
复制
tomato = load("tomato")

而不是。

票数 0
EN

Stack Overflow用户

发布于 2017-05-02 20:20:24

如果您想加载这么多图像,请使用os.listdir并将目录中的所有图像放入字典中。此外,请在加载图像后使用convertconvert_alpha来提高性能。

代码语言:javascript
复制
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

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43732487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档