使用pygame在cx_Freeze中包含整个文件夹

2024-09-30 22:28:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在学习如何为pygame文件夹进行cx_冻结设置的教程。这是我想到的

import cx_Freeze
executables = [cx_Freeze.Executable("mainGame - Copy.py")]
cx_Freeze.setup(
    name = "Cave",
    version = "1.0",
    author = "Owen Pennington",
    options = {"build_exe": {"packages":["pygame"], "include_files":["floor_heart.wav"]}},
    executables = executables
    )

但是,我的其余文件都在文件夹中。然后在这些文件夹中有一些文件夹。例如,我有一个文件夹(路径目录)C:CaveGame\Sprites,这个文件夹包含许多其他文件夹,C:CaveGame\Sprites\FloorsC:CaveGame\Sprites\Lava等等。。。然后我还有一个文件夹C:CaveGame\Music,里面保存着我所有的音乐文件和音效。我怎样才能让这些都在设置中工作


Tags: namepyimport文件夹setup教程pygamecx
1条回答
网友
1楼 · 发布于 2024-09-30 22:28:31

您只需要在options字典中包含上层目录项:

setup(name='Widgets Test',
      version = '1.0',
      description = 'Test of Text-input Widgets',
      author = "Fred Nurks",
      options = { "build_exe": {"packages":["pygame"], "include_files":["assets/", "music/"] } },
      executables = executables
      )

上面的示例将包括文件assets/images/blah.pngmusic/sounds/sproiiiing.ogg及其正确的目录该顶级文件夹下的所有内容都被拉入lib/

当您要加载这些文件时,有必要计算出文件的确切路径。但通常的方法不适用于cxFreeze。参考https://cx-freeze.readthedocs.io/en/latest/faq.html~

if getattr(sys, 'frozen', False):
    EXE_LOCATION = os.path.dirname( sys.executable ) # frozen
else:
    EXE_LOCATION = os.path.dirname( os.path.realpath( __file__ ) ) # unfrozen

显然,您需要模块sysos.path来实现这一点

然后在加载文件时,使用os.path.join确定完整路径:

my_image_filename = os.path.join( EXE_LOCATION, "assets", "images", "image.png" )
image = pygame.image.load( my_image_filename ).convert_alpha()

编辑:如果您是在Windows下构建,则还需要包含Visual C运行时:https://cx-freeze.readthedocs.io/en/latest/faq.html#microsoft-visual-c-redistributable-package。将include_msvcr添加到options

options = { "build_exe": { "include_msvcr", "packages":["pygame"] #... 

相关问题 更多 >