![](/img/trans.png)
[英]Pyinstaller: generate -exe file + folder (in --onefile mode)
[英]Add folder of images to onefile exe using pyinstaller
我的應用程序使用文件夾“圖像”中的圖像我在整個應用程序中訪問這些圖像,我想將它添加到我的 onefile exe 中。 問題是當我嘗試運行我的文件時,它會出錯,除非我將圖像文件夾添加到與 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 中提取圖像。 謝謝
當您嘗試使用.
,您正在嘗試根據您當前的工作目錄(例如,終端所在的目錄)執行此操作。 但是,當您使用 Pyinstaller 時,您的代碼會丟失引用並且無法訪問正確的目錄。 有關此主題的文檔要廣泛得多。
在編程中,使用相對路徑不是一個好主意。 如果您使用的是 Pyinstaller,這是一個糟糕的主意。 您可能想使用常量__file__
來檢查實際文件位置, 但它也不起作用。
我使用 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__
的東西並不神奇! 它來自文檔。os.path.join
將生成一個操作系統感知路徑,因此os.path.join("a", "b")
將在 Linux/Mac 上生成a/b
,在 Windows 上生成a\b
,所以使用這個或Pathlib
你可以。 最后,一個提示。 您不需要每次都重復整個pyinstaller
命令(可能很長)。 一旦你有了myapp.spec
,你就可以做pyinstaller myapp.spec -y
( -y
跳過關於覆蓋dist/
的確認消息),你就完成了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.