如何将 TrueType 字体文件添加到 pyinstaller 可执行文件以供 Pygame 使用?

How to add a TrueType font file to a pyinstaller executable for use with Pygame?

我创建了一个名为 breakout.py 的 python 文件,并想用 pyinstaller 创建一个 exe。 python 文件需要文件 ARCADECLASSIC.TTF 与 python 脚本位于同一目录中,以便 运行。此外,我希望能够 运行 exe 文件,而不必同时拥有字体文件。我已经尝试了多个 pyinstaller 命令来尝试执行此操作。

我尝试了此命令 pyinstaller --add-binary "ARCADECLASSIC.TTF;." --onefile breakout.py 并收到权限被拒绝的错误编号 13。

然后我尝试编辑我的代码,使字体文件位于一个名为 fonts 的目录中,并尝试了这个命令 pyinstaller --add-binary "fonts/ARCADECLASSIC.TTF;fonts" --onefile breakout.py 运行 没有错误,但是当我 运行 exe 文件出现错误,说没有名为 fonts/ARCADECLASSIC.TTF 的文件,所以崩溃了。

我现在也试过指定字体文件的完整目录,但还是不行。

如果这对我有帮助,我的 OS 是 Windows,我正在使用 python 3.8.5 64 位和 pyinstaller 4.0。

首先是我正在尝试做的事情,其次是如果可能的话我该怎么做以及我做错了什么。

您需要创建一个 .spec 文件并说明您要在其中包含的内容,例如字体或其他图像。

# -*- mode: python -*-

block_cipher = None


a = Analysis(['your python file.py'],
             pathex=['C:\path\to\directory'], # just the directory not the file
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

a.datas += [('ttf file','path\to\ttf\file', "DATA")]

pyz = PYZ(a.pure, a.zipped_data,
         cipher=block_cipher)

exe = EXE(pyz,
      a.scripts,
      a.binaries,
      a.zipfiles,
      a.datas,
      name='Your App Name',
      debug=False,
      strip=False,
      upx=True,
      console=False # set True if command prompt window needed
)

在游戏所在的实际 python 文件中包含此内容。

def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

每当你想加载你的字体时都这样做。

font = pygame.font.Font(resource_path("Font.ttf"), size)

在你的主 python 文件中有了它之后,在你的终端中输入你创建的规范文件。

pyinstaller yourspecfile.spec

这将创建您的可执行文件,它应该会自动运行。

这是我之前项目的规范文件的样子 # -- 模式:python --

block_cipher = None


a = Analysis(['lol.py'],
         pathex=['C:\games\snake'],
         binaries=[],
         datas=[],
         hiddenimports=[],
         hookspath=[],
         runtime_hooks=[],
         excludes=[],
         win_no_prefer_redirects=False,
         win_private_assemblies=False,
         cipher=block_cipher)

a.datas += [('8min.ttf','C:\games\snake\8min.ttf', "DATA")]

pyz = PYZ(a.pure, a.zipped_data,
         cipher=block_cipher)

exe = EXE(pyz,
      a.scripts,
      a.binaries,
      a.zipfiles,
      a.datas,
      name='Snake',
      debug=False,
      strip=False,
      upx=True,
      console=False)