我想通过使用pyinstaller将.py文件转换为exe文件

时间:2018-12-28 13:22:14

标签: python python-3.x pygame anaconda pyinstaller


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

↓我收到错误消息(它说没有名为“ resources”的文件夹!但是我确实制作了虚拟文件夹。)
https://imgur.com/sq67mil

如何解决此问题?

(我引用了本文档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 )

2 个答案:

答案 0 :(得分:0)

运行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。如果执行此操作,则无需修改脚本文件。另一个好处是,您的游戏的启动时间可能会更短(因为不需要解压缩文件)。

答案 1 :(得分:0)

@Bobsleigh的回答有帮助 https://stackoverflow.com/a/36456473

您基本上需要向.spec文件中添加数据并运行“ pyinstaller my_spec_file”(假设您要一个目录捆绑而不是一个文件exe,因为这两个访问pyinstaller文档之间的区别)

相关问题