pygame.image.load('sprite/test_bg.jpg'):pygame.error:无法打开sprite/test_bg.jpg [英] pygame.image.load('sprite/test_bg.jpg'): pygame.error: Couldn't open sprite/test_bg.jpg
问题描述
Import pygame
pygame.init()
BG = pygame.image.load('_pycache_/test_bg.jpg')
def DrawGameWin():
window.blit(BG,(0,0))
pygame.display.update()
DrawGameWin()
推荐答案
图像文件路径必须相对于当前工作目录.工作目录可能与python文件的目录不同.
The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
文件的名称和路径可以通过 os.getcwd()
进行获取,并可以通过 os.chdir(path)
.
The name and path of the file can be get by __file__
. The current working directory can be get by os.getcwd()
and can be changed by os.chdir(path)
.
一种解决方案是更改工作目录:
One solution is to change the working directory:
import os
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)
另一种解决方案是找到绝对路径. 如果图像相对于python文件的文件夹(甚至在同一文件夹中),则可以获取文件目录并加入(
An alternative solution is to find the absolute path.
If the image is relative to the folder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()
) the image filename. e.g.:
import pygame
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
# join the filepath and the filename
imgPath = os.path.join(sourceFileDir, 'test_bg.jpg')
# imgPath = os.path.join(sourceFileDir, '_pycache_/test_bg.jpg')
surface = pygame.image.load(imgPath)
这篇关于pygame.image.load('sprite/test_bg.jpg'):pygame.error:无法打开sprite/test_bg.jpg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!