使用pygame.image.load()时出错

4 投票
1 回答
4523 浏览
提问于 2025-04-17 19:49

当我尝试从另一个文件夹加载一张图片时,我遇到了这个错误...

pygame.error: 无法打开 sprites/testtile.png

如果图片在同一个文件夹里,我可以正常加载 .png 文件,但一旦它们在另一个文件夹里,我就会遇到这个错误。

我知道 Python 也能访问那个文件夹,因为我从那个文件夹导入 .py 文件时没有任何错误。

当我尝试使用 pygame.image.get_extended 时,它返回的是 0,但从同一个文件夹加载 .png 文件没有问题,所以我觉得这不是导致问题的原因。

顺便说一下,我是在使用 PyCharm,这种情况总是让我在这个开发环境中遇到麻烦。我甚至觉得这不是 pygame 的问题。现在我真的不知道该怎么办。

文件夹结构:

scripts/GraphicsDriver.py

sprites/testtile.png

这个驱动程序正在尝试访问 testtile.png 文件

1 个回答

3

你的sprites文件夹是在GraphicsDriver.py这个文件的同一个目录下吗?使用PyGame加载图片时可能会遇到一些问题。PyGame会在它被初始化的目录中寻找文件。你可以用'os.path.join'来指定文件的绝对路径。

不过我通常会自己写一个简单的图片加载器,这样可以让过程更灵活。像这样,它会返回图片和一个矩形区域:

def load_image(name, colorkey = None):
    """loads an image and converts it to pixels. raises an exception if image not found"""
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', name
        raise SystemExit, message
    image = image.convert()
    # set the colorkey to be the color of the top left pixel
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()

希望这能帮到你。

撰写回答