Pygame在子目录中找不到图像文件夹 [英] Pygame not finding image folder when in subdirectory

查看:63
本文介绍了Pygame在子目录中找不到图像文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在重构我的游戏,以便将一些文件放置在名为/lib/[下面的文件结构] 的子目录中.

I've been refactoring my game so that some files are placed in a subdirectory called /lib/ [File Structure below].

其中两个文件是一个名为 media.py 的 python 文件,以及一个名为 media 的文件夹.Media.py 几乎是几行代码:

Two of these files are a python file called media.py, and a folder just called media. Media.py is pretty much a couple lines of this code:

blue = pygame.image.load(os.path.join('media', 'blue.png')).convert_alpha()

当我将 media.py 和 media 文件夹放在 lib 中并运行 media.py 时,它运行良好,没有错误.

When I placed media.py and the media folder in lib and run media.py, It works perfectly fine, no errors.

但是当我运行 Main.py 并尝试调用和导入 Media.py 时,它会引发错误,指出 media.py 无法在媒体文件夹中找到任何文件,即使它们位于同一子目录中,并且之前工作得很好.

But when I run Main.py, and It tries to call and import Media.py, It raises an error saying that media.py cannot find any file within the media folder, even when they are in the same subdirectory, and worked perfectly fine before.

我尝试使用完整文件路径和 os.path.abspath 但它们也不起作用,并引发相同的错误.

I've tried to use the full file path and os.path.abspath but they dont work either, and raise the same errors.

这是在 main.py 中引发错误的区域:

Here is the area that raises the error in main.py:

sys.path.insert(0, './lib')
import media

这是我的文件结构:

Game
|
| - Lib
|   |
|   | - Media
|   |       |
|   |       blue.png, along with many other images
|   Media.py
|   |
|   Fetch.py
|   |
|   gamewide.py

推荐答案

你的代码依赖于起始目录.

your code depends on the start directory.

为了与此无关,您可以使用图像文件与 Media.py__file__ 对象的目录名称在同一目录中这一事实

To be independent from that you could use the fact that the image file is in the same directory as Media.py and the dir name of __file__ object

那么:

blue = pygame.image.load(os.path.join(os.path.dirname(__file__), 'Media','blue.png')).convert_alpha()

会解决问题

这篇关于Pygame在子目录中找不到图像文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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