创建可执行文件pygame时遇到问题-pyinstaller

时间:2019-02-05 08:02:15

标签: audio pygame executable 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

1 个答案:

答案 0 :(得分:0)

.spec文件是什么样的?这是PyInstaller docs on adding data files

基本上,您需要添加以下内容:

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"))