我的应用程序使用文件夹“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文件所在的路径并寻找实际的Images文件夹。我希望它实际上从 EXE 中提取图像。 谢谢
答案 0 :(得分:1)
当您尝试使用 .
访问文件时,您正在尝试根据您的当前工作目录(例如,可以是终端所在的目录)执行此操作里面)。但是,当您使用 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"))
__DIR__
的东西并不神奇!它来自documentation。os.path.join
会产生一个操作系统感知路径,所以 os.path.join("a", "b")
在 Linux/Mac 上会产生 a/b
,在 Windows 上会产生 a\b
,所以使用这个或 {{3} } 尽你所能。最后,一个提示。您不需要每次都重复整个 pyinstaller
命令(可能很长)。获得 myapp.spec
后,您只需执行 pyinstaller myapp.spec -y
(-y
跳过有关覆盖 dist/
的确认消息)即可完成。