无法打开资源文件:pygame.error:无法打开sprite/test_bg.jpg [英] Could not open resource file: pygame.error: Couldn't open sprite/test_bg.jpg

查看:56
本文介绍了无法打开资源文件:pygame.error:无法打开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 resource (image, font, sound, etc.) 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 file is in an subfolder 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 relative filepath. 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
filePath = os.path.join(sourceFileDir, 'test_bg.jpg')
# filePath = os.path.join(sourceFileDir, '_pycache_/test_bg.jpg')

surface = pygame.image.load(filePath)

这篇关于无法打开资源文件:pygame.error:无法打开sprite/test_bg.jpg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆