使用pyinstaller将图像文件夹添加到onefile exe

2024-10-03 19:23:57 发布

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

我的应用程序使用文件夹“images”中的图像我在整个应用程序中访问这些图像,并希望将其添加到onefile exe中。问题是,当我尝试运行我的文件时,它会出错,除非我将Images文件夹添加到与exe相同的位置,这样我就知道它添加不正确。 我相信这可能与我到达目的地的方式有关

下面是我目前在应用程序中获取图像的方式

tkinter.PhotoImage(file =  "./Images/btnOK.png")

下面是我如何生成我的exe

 pyinstaller --onefile --windowed --add-data C:/Users/Paul_Program_Machine/Documents/Python_Code/GuiTests/Images/*'; 'Images" myapp.py

编辑:规范文件

# -*- mode: python ; coding: utf-8 -*-

block_cipher = None


a = Analysis(['myapp.py'],
             pathex=['C:\\Users\\Paul_Program_Machine\\Documents\\Python_Code\\GuiTests'],
             binaries=[],
             datas=[('C:\\Users\\Paul_Program_Machine\\Documents\\Python_Code\\GuiTests\\Images\\*', 'Images')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='myapp',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False )

它的实际路径是EXE文件,正在查找实际的图像文件夹。我希望它能从EXE中提取图像。 谢谢


Tags: 文件图像文件夹false应用程序codemachineprogram
1条回答
网友
1楼 · 发布于 2024-10-03 19:23:57

当您尝试使用.访问文件时,您正在尝试基于当前工作目录(例如,终端所在的目录)访问文件。但是,当您使用Pyinstaller时,您的代码将丢失引用,无法访问正确的目录The documentation在这个主题上要广泛得多

在编程中,使用相对路径不是一个好主意。如果您使用的是Pyinstaller,这是一个非常糟糕的想法。您可能希望使用常量__file__来检查实际的文件位置but it'll also not work

我使用Pyinstaller解包和打包的方式如下:

import os
# __DIR__ contains the actual directory that this file is in.
__DIR__ = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))

# ...

# Now you can access your image this way (and it will work on all platforms 😃):
tkinter.PhotoImage(file =  os.path.join(__DIR__, "Images", "btnOK.png"))
  • 这些东西不是魔法!它来自documentation
  • os.path.join将产生一个操作系统感知路径,因此os.path.join("a", "b")将在Linux/Mac上产生a/b,在Windows上产生a\b,所以在可以的地方使用这个或^{}

最后,还有一个提示。您不需要每次都重复整个pyinstaller命令(可能很长)。一旦你有了你的myapp.spec,你可以只做pyinstaller myapp.spec -y-y跳过关于覆盖的确认消息dist/),你就完成了

相关问题 更多 >