首页 > 解决方案 > 创建可执行pygame的问题 - pyinstaller

问题描述

我最近开始为我的女儿制作一个游戏来帮助我学习单词。我继续前进并决定创建可执行文件(我将在许多其他游戏中这样做)。由于声音和音乐,这款游戏有些不同。我已经尝试了我能想到的一切,搜索了我能想到的一切等等。这是 CMD 报告的错误,错误是指声音文件。我尝试直接添加文件,--add-data我尝试将可执行文件放在与声音文件相同的目录中(不应该需要,因为它应该已经捆绑了它)。否则脚本运行得非常好(来自 CMD 等)任何想法?

C:\Users\launc\Desktop\Coding\Games\g_sight_words\dist>sight_words.exe pygame 1.9.4 Hello from the pygame community. https://www.pygame.org/contribute.html Traceback (most recent call last): File "sight_words.py", line 5, in <module> File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "c:\users\launc\appdata\local\programs\python\python37-32\lib\site- packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module exec(bytecode, module.__dict__) File "settings.py", line 21, in <module> pygame.error: Unable to open file 'the.wav' [9892] Failed to execute script sight_words

标签: audiopygameexecutablepyinstaller

解决方案


您的 .spec 文件是什么样的?这是有关添加数据文件的 PyInstaller 文档

基本上你需要添加类似的东西:

a = Analysis(...
 datas=[ ('the.wav', '.') ],
 ...
 )

这会将您的声音文件('the.wav')放入已编译应用程序的根目录(第二个参数,'.')

然后在您的应用程序中,您可以检查您是从源代码运行还是作为已编译的可执行文件运行。我使用一个辅助函数:

def my_path(path_name):
    """Return the appropriate path for data files based on execution context"""
    if getattr( sys, 'frozen', False ):
        # running in a bundle
        return(os.path.join(sys._MEIPASS, path_name))
    else:
        # running live
        return path_name

因此,您的应用程序代码将如下所示:

the_sound = pygame.mixer.Sound(my_path("the.wav"))

推荐阅读