Python 为什么它说不能';在Pygame上打开shooting\u game\player.png?
为什么它说不能在Pygame上打开shooting\u game\player.png? 以下是我目前的代码:Python 为什么它说不能';在Pygame上打开shooting\u game\player.png?,python,python-3.x,pygame,Python,Python 3.x,Pygame,为什么它说不能在Pygame上打开shooting\u game\player.png? 以下是我目前的代码: import pygame import os width, height = 500, 400 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("Shooter Game") player = pygame.image.load(os.path.join
import pygame
import os
width, height = 500, 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Shooter Game")
player = pygame.image.load(os.path.join("shooter_game", "player.png"))
这给了我一个错误:
Exception has occurred: error
Couldn't open shooter_game/player.png
File "C:\python_games\shooter_game\game.py", line 11, in <module>
player = pygame.image.load(os.path.join("shooter_game", "player.png"))
发生异常:错误
无法打开shooter\u game/player.png
文件“C:\python\u games\shooter\u game\game.py”,第11行,在
player=pygame.image.load(os.path.join(“shooter\u game”、“player.png”))
我确保player.png
的文件夹是
在与game.py
文件夹相同的文件夹中
有人能帮我解决这个问题吗
谢谢。如果
player.png
与game.py
在同一文件夹中,您应该在shooter\u game
目录中查找:
player=pygame.image.load(“player.png”)
如果player.png
与game.py
位于同一文件夹中,则应在shooter\u game
目录中查找:
player=pygame.image.load(“player.png”)
相对路径基于当前工作目录,而不是脚本的目录。如果您碰巧更改了脚本的目录以运行它,那么它们都是相同的,并且它可以正常工作。否则你会得到这个错误。Python脚本有一个保存脚本文件名的\uu文件
变量。您可以利用它来查找目录
player = pygame.image.load(os.path.join(
os.path.dirname(os.path.abspath(__file__))),
"player.png")
pathlib
有另一种处理文件系统路径的方法
from pathlib import Path
player = pygame.image.load(Path(__file__).absolute().parent/"player.png")
相对路径基于当前工作目录,而不是脚本的目录。如果您碰巧更改了脚本的目录以运行它,那么它们都是相同的,并且它可以正常工作。否则你会得到这个错误。Python脚本有一个保存脚本文件名的
\uu文件
变量。您可以利用它来查找目录
player = pygame.image.load(os.path.join(
os.path.dirname(os.path.abspath(__file__))),
"player.png")
pathlib
有另一种处理文件系统路径的方法
from pathlib import Path
player = pygame.image.load(Path(__file__).absolute().parent/"player.png")
我确实查看了
shooter\u game
文件夹,但仍然不起作用。我确实查看了shooter\u game
文件夹,但仍然不起作用。