python - 我想使用 pyinstaller 将 .py 文件制作成 exe 文件

标签 python python-3.x pygame anaconda pyinstaller


我正在使用 pygame 制作一个程序,并希望将其制作成可执行文件。
如果是python脚本,程序会正确运行。
但是,如果我试图将其作为可执行文件,就会出现问题。
我制作了一个如下所示的规范文件,并运行它以将所有依赖项捆绑到可执行文件中。
最后,我可以制作可执行文件,但它运行失败并显示错误消息,如下所示。

↓我收到错误消息(它说没有名为“resources”的文件夹!但我确实创建了虚拟文件夹。)
/image/Renmu.jpg

如何解决这个问题?

(我引用了这个文档 https://pyinstaller.readthedocs.io/en/v3.3.1/spec-files.html )

PyInstaller版本:3.3.1
Python版本:3.6.6

↓我的Python脚本

#pygame_test.py located at Desktop/RPG_test
import pygame,sys,os
print(os.getcwd())
class Player(pygame.sprite.Sprite):
    def __init__(self,image_path,root):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image_path).convert_alpha()
        self.rect = self.image.get_rect()

    def update(self):
        self.rect.centerx = pygame.mouse.get_pos()[0]
        self.rect.centery = pygame.mouse.get_pos()[1]

def main():
    pygame.init()
    root = pygame.display.set_mode((400,400))
    running = True
    player = Player("resources/tiger_window.png",root)
    group = pygame.sprite.Group()
    group.add(player)
    fps = 30
    clock = pygame.time.Clock()
    while running:
        clock.tick(fps)
        root.fill((50,150,200))
        group.update()
        group.draw(root)
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                running = False
                pygame.quit()
                sys.exit()
        pygame.event.clear()
if __name__ == "__main__":
    main()

↓我通过“pyi-makespec”命令制作的spec文件。

# -*- mode: python -*-
block_cipher = None
a = Analysis(['pygame_test.py'],
         pathex=['C:\\Users\\Ayata\\Desktop\\RPG_test'],
         binaries=[],
         datas=[("C:/Users/Ayata/Desktop/RPG_test/resources/tiger_window.png","resources")],
         hiddenimports=[],
         hookspath=[],
         runtime_hooks=[],
         excludes=[],
         win_no_prefer_redirects=False,
         win_private_assemblies=False,
         cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
         cipher=block_cipher)
exe = EXE(pyz,
      a.scripts,
      a.binaries,
      a.zipfiles,
      a.datas,
      name='pygame_test',
      debug=False,
      strip=False,
      upx=True,
      runtime_tmpdir=None,
      console=True )

最佳答案

运行 PyInstaller 构建的单文件可执行文件后发生的第一件事是 a temporary directory is created 。然后,可执行文件将一堆资源文件以及自定义数据文件(如您的 tiger_window.png 文件)解压到此目录中。在您的脚本中,您可以从变量 sys._MEIPASS 检索此目录的路径。

以下代码片段应在“开发”模式和“卡住”模式下提供图像文件的正确路径:

try:
    # Get temporary directory created by PyInstaller single-file executable
    base_path = sys._MEIPASS
except AttributeError:
    # Get directory in which this script file resides
    base_path = os.path.dirname(os.path.realpath(__file__))

# Get path to image file
img_path = os.path.join(base_path, 'resources/tiger_window.png')

替代解决方案

您还可以让 PyInstaller freeze your script into a directory (with multiple files) instead of just one single executable 。如果您这样做,则无需对脚本文件进行修改。另一个好处是游戏的启动时间可能会更短(因为不需要解压文件)。

关于python - 我想使用 pyinstaller 将 .py 文件制作成 exe 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53959278/

相关文章:

python - 在 Pandas DataFrame 中格式化 Float64Index

python - "NameError: name ' sqlalchemy中的 float ' is not defined"

python-3.x - Python3 - 以编程方式更改 PSD 图层的可见性

python3.6 : KeyError: 'formatters'

python - 如何从 pygame.surface 获取 RGB 颜色的 numpy 数组

python - 为什么pygame不会画圆?

python - 闲置3秒后如何再次移动一圈?

python - Pandas 连接 : cannot reindex from a duplicate axis

python - Python 重启后 Gzip 输出不同

python-3.x - 运行时错误 : matplotlib does not support generators as input