我是编程新手,所以我给自己提出了创建 Pong 的挑战,所以我做到了。现在我想与几个 friend 分享它,所以我决定尝试使用 pyinstaller (已经尝试过 cx_Freeze)。 在这个 Pong 游戏中,我有 3 个音效,位于“sfx”文件夹中。所以我研究了使用 pyinstaller 包含文件,所以我的 .spec 文件显示:
added_files = [
('E:\Game Development Stuff\Python 3\Games\Pong\sfx\hitOutline.ogg', 'sfx'),
('E:\Game Development Stuff\Python 3\Games\Pong\sfx\hitPaddle.ogg', 'sfx'),
('E:\Game Development Stuff\Python 3\Games\Pong\sfx/score.ogg', 'sfx')
]
a = Analysis(['pong.py'],
pathex=['E:\\Game Development Stuff\\Python 3\\Games\\Pong'],
binaries=None,
datas=added_files,
在 Pong 程序本身中,我使用以下代码来获取路径:
def resource_path(relative):
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(relative)
fileDir = os.path.dirname(os.path.realpath('__file__'))
hitPaddle = resource_path(os.path.join(fileDir, "sfx", "hitPaddle.ogg"))
hitOutline = resource_path(os.path.join(fileDir, "sfx", "hitOutline.ogg"))
score = resource_path(os.path.join(fileDir, "sfx", "score.ogg"))
hitPaddleSound=pygame.mixer.Sound(hitPaddle)
hitOutlineSound=pygame.mixer.Sound(hitOutline)
scoreSound=pygame.mixer.Sound(score)
所以我使用 pyinstaller 制作 exe 文件(使用命令 pyinstaller pong.spec) 但是当我打开 pong.exe 文件时,命令窗口显示:
Traceback "<string>", Unable to open file 'E:\\Game Development Stuff\\Python 3\\Games\\Pong\\dist\\pong\\sfx\\hitPaddle.ogg'
但在完全相同的路径中是 hitPaddle.ogg。 在我看来,pygame 由于某种奇怪的原因无法找到它?
最佳答案
我认为问题出在这一行。您没有正确引用文件。您写道:
hitPaddle = resource_path(os.path.join(fileDir, "sfx", "hitPaddle.ogg"))
相反,你应该:
hitpaddle = resource_path("sfx\hitPaddle.ogg")
这是因为当您在规范文件中添加文件时,您声明它们应该位于“root\sfx”文件夹中。当.exe以onefile模式运行时,所有文件实际上都位于名为MEIXXXX的临时文件夹中,其中XXXX是一些整数。当您运行 .exe 时,如果您打开此文件夹,您应该能够在其中看到您的文件。
关于python - 使用 pyinstaller 在 pygame 脚本中包含声音文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37126295/