作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Import pygame
pygame.init()
BG = pygame.image.load('_pycache_/test_bg.jpg')
def DrawGameWin():
window.blit(BG,(0,0))
pygame.display.update()
DrawGameWin()
最佳答案
资源(图像、字体、声音等)文件路径必须相对于当前工作目录。工作目录可能与python文件的目录不同。
将文件放在同一目录或子目录中是不够的。您还需要设置工作目录。或者,您可以创建绝对文件路径。
文件名和路径可以通过__file__
获取。当前工作目录可以通过 os.getcwd()
获取可以通过 os.chdir(path)
进行更改:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
另一种解决方案是查找绝对路径。如果该文件位于 python 文件的子文件夹中(甚至位于同一文件夹中),那么您可以获取该文件的目录并加入( os.path.join()
)相对文件路径。例如:
import pygame
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
# join the filepath and the filename
filePath = os.path.join(sourceFileDir, 'test_bg.jpg')
# filePath = os.path.join(sourceFileDir, '_pycache_/test_bg.jpg')
surface = pygame.image.load(filePath)
<小时/>
使用 pathlib
也可以实现同样的效果模块。更改工作目录
import os, pathlib
os.chdir(pathlib.Path(__file__).resolve().parent)
或创建绝对文件路径:
import pathlib
# [...]
filePath = pathlib.Path(__file__).resolve().parent / 'test_bg.jpg'
surface = pygame.image.load(filePath)
关于python - 无法打开资源文件,pygame错误: "FileNotFoundError: No such file or directory.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58177145/
我是一名优秀的程序员,十分优秀!