无法打开资源文件,pygame 错误:“FileNotFoundError: No such file or directory." [英] Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."

查看:30
本文介绍了无法打开资源文件,pygame 错误:“FileNotFoundError: No such file or directory."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

文件名和路径可以通过__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文件的子文件夹中(甚至在同一个文件夹中),那么你可以获取文件的目录并加入(os.path.join()) 相对文件路径.例如:

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 错误:“FileNotFoundError: No such file or directory."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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