不确定我做错了什么,我正在学习如何使用Python和PyGame制作游戏,我收到错误:
pygame.error: Couldn't open resources/images/dude.png
我的代码如下:
import pygame
from pygame.locals import *
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width,height))
player = pygame.image.load("resources/images/dude.png")
while 1:
screen.fill(0)
screen.blit(player, (100,100))
pygame.display.flip()
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit(0)
完整的错误消息是:
ALSA lib confmisc.c:768:(parse_card) cannot find card '0'
ALSA lib conf.c:4292:(_snd_config_evaluate) function
snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4292:(_snd_config_evaluate) function snd_func_concat
returned error: No such file or directory
ALSA lib confmisc.c:1251:(snd_func_refer) error evaluating name
ALSA lib conf.c:4292:(_snd_config_evaluate) function snd_func_refer
returned error: No such file or directory
ALSA lib conf.c:4771:(snd_config_expand) Evaluate error: No such file or
directory
ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM default
Traceback (most recent call last):
File "/root/Documents/PyGame/game.py", line 9, in <module>
player = pygame.image.load("resources/images/dude.png")
pygame.error: Couldn't open resources/images/dude.png
答案 0 :(得分:2)
改为使用相对路径(这样做总是更好):
import os
current_path = os.path.dirname(__file__) # Where your .py file is located
resource_path = os.path.join(current_path, 'resources') # The resource folder path
image_path = os.path.join(resource_path, 'images') # The image folder path
通过这样做,无论您何时移动包含.py
文件的文件夹,其子目录(以及它们包含的内容)仍然可以访问,而无需您修改代码。
最终代码:
import pygame
import os
from pygame.locals import *
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
current_path = os.path.dirname(__file__) # Where your .py file is located
resource_path = os.path.join(current_path, 'resources') # The resource folder path
image_path = os.path.join(resource_path, 'images') # The image folder path
player_image = pygame.image.load(os.path.join(image_path, 'dude.png'))
while 1:
screen.fill(0)
screen.blit(player, (100,100))
pygame.display.flip()
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit(0)
对所有其他文件使用此访问方法,您将避免一系列问题。
答案 1 :(得分:0)
要使其在没有相对路径的情况下工作,您需要将创建的.py文件放置在pygame文件夹中。资源文件夹也应该存在。
答案 2 :(得分:0)
您可以尝试以下实现。
代码:
img = ".\\resources\\images\\dude.png"
img2 = pygame.image.load(img)
答案 3 :(得分:-2)
Python在程序所在的同一文件夹中查找文件。你写的代码说你在你的程序所在的文件夹中有一个名为resources的文件夹,其中有一个名为images的文件夹。如果是这种情况,我无法帮助你,但是如果不是,则使用完整的文件位置。
答案 4 :(得分:-2)
在您的路径中添加 ./ 。
player = pygame.image.load("./resources/images/dude.png")
答案 5 :(得分:-3)
您需要做的就是将这张图片放在代码文件所在的文件夹中。但这是针对Linux