Pygame在子目录中找不到图像文件夹

编程入门 行业动态 更新时间:2024-10-12 03:16:13
本文介绍了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在子目录中找不到图像文件夹

本文发布于:2023-11-28 14:59:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642882.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子目录   中找   文件夹   图像   Pygame

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!