【问题标题】:How to change to get python to read images inside multiple folders如何更改以让 python 读取多个文件夹中的图像
【发布时间】:2019-09-20 23:22:26
【问题描述】:

我正在尝试在 python 中显示图像,但每当我尝试时,我都会收到此错误:

Traceback (most recent call last):
  File "C:/Users/Brandon/PycharmProjects/UnstableUnicorns/UnstableUnicorns Test.py", line 15, in <module>
    BabyNarwhal = pygame.image.load(r'CardImages\BasicDeck\BabyUnicorns\Baby Narwhal.png').convert()
pygame.error: Couldn't open CardImages\BasicDeck\BabyUnicorns\Baby Narwhal.png

我同意图像路径有点复杂,但我似乎找不到让它加载文件的方法。我尝试输入整个文件路径,尝试更改读取位置,但似乎无法加载此图像。我真的不想将图像与代码放在同一个文件夹中,因为我想显示很多不同的图像。这是我的代码:

import pygame

pygame.init()

xDisplay = 1000
yDisplay = 500

white = (255, 255, 255)

BabyNarwhal = pygame.image.load(r'CardImages\BasicDeck\BabyUnicorns\Baby Narwhal.png').convert()


def main():
    display = pygame.display.set_mode((xDisplay, yDisplay))

    while True:
        display.fill(white)

        display.blit(BabyNarwhal, (0, 0))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            pygame.display.update()


main()

这是完整的图像路径:

C:\Users\Brandon\PycharmProjects\UnstableUnicorns\CardImages\BasicDeck\BabyUnicorns

【问题讨论】:

标签: python image pygame


【解决方案1】:

不建议在文件名中使用空格。并且使用 '/' 而不是 '\' 可以解决该错误。 所以,你应该重命名你的图像,不带空格,并使用:

babynarwhal_img = pygame.image.load(CardImages/BasicDeck/BabyUnicorns/BabyNarwhal.png).convert()

注意:由于文件夹同名,修改了变量名,可能会导致某些版本出现问题。

【讨论】:

    猜你喜欢
    • 2018-09-07
    • 2021-05-28
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 2023-03-06
    • 2011-07-25
    相关资源
    最近更新 更多