1

Is there a way to pass an argument in Pygame using "pygame.image.load" without the source folder having to be in the C drive, or the scripts and images to be in the C drive?

I have tried many different things and spent much of this weekend trying to figure it out. I've searched over other stackoverflow Q&As and haven't gotten anywhere.

I have tried using "os.path.join", "os.path.normpath", and the like, and I still haven't figured it out.

Here's the code:

import os, pygame
load_image = pygame.image.load(os.path.join('\\test', 'energy.png'))

And it works fine as long as the "test" folder is located in C:\, but as soon as I move it to any other location I get the ol' pygame.error: Couldn't open \test\energy.png error.

Basically what I'm asking is: Is there anyway to get a Pygame script (specifically the pygame.image.load code) to work without having the folder, script, and images all located in C:\?

Eventually I want to make a cx_freeze app of the game I'm working on, and I want the user to be able to place the folder in any location he desires.

I'm using Python 3.3 on a Windows 7 laptop. Thanks.

4

2 回答 2

2

最后!好的,我想通了。

除了导入其他模块之外,您还需要包含此代码以使其工作并加载不在 C:\ 中的图像:

import os
from os.path import dirname, realpath, abspath

这是我的最终代码:

__file__ = "game_folder"    # <-- This code is needed for CX_freeze, to avoid NameError.
file_path = os.path.join(dirname(__file__), "images", "energy.png")

谢谢你的帮助!

于 2013-11-02T15:22:22.067 回答
2

假设您的 python 脚本位于

f:/bar/game.py

energy.png

f:/bar/images/energy.png

game.py然后会使用

path = os.path.join("images", "energy.png")
energy = pygame.image.load(path)
于 2013-10-28T06:57:50.863 回答