Python Pyinstaller 和 --onefile:如何在 exe 文件中包含图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31836104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pyinstaller and --onefile: How to include an image in the exe file
提问by Nautilius
I have created an exe file using Pyinstaller.
我已经使用 Pyinstaller 创建了一个 exe 文件。
pyinstaller.exe --onefile --icon='Loco.ico program.py
In the program, I include an image in my plots, and when I run the program alone in its folder, I get the following:
在程序中,我在绘图中包含了一个图像,当我在其文件夹中单独运行该程序时,我得到以下信息:
IOError: [Errno 2] No such file or directory: 'Logo.png'
One solution is to include the image in the folder of the exe as seen in the link below:
一种解决方案是将图像包含在 exe 文件夹中,如下面的链接所示:
pyinstaller does not show images and icon
But then again the whole point of --onefile is to have exactly that, not need the image in addition. I think the solution may be in this link, but I haven't understood it.
但话又说回来, --onefile 的重点是完全有,不需要另外的图像。我认为解决方案可能在此链接中,但我还没有理解。
Bundling data files with PyInstaller (--onefile)
使用 PyInstaller (--onefile) 捆绑数据文件
my spec file looks the following:
我的规范文件如下所示:
# -*- mode: python -*-
a = Analysis(['AMOS_Visualizer.py'],
pathex=['C:\Users\elu\PycharmProjects\Prosjektet\Forsok splitting'],
hiddenimports=[],
hookspath=None,
runtime_hooks=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='AMOS_Visualizer.exe',
debug=False,
strip=None,
upx=True,
console=True , icon='AMOS.ico')
采纳答案by Nautilius
Edit:
编辑:
I belive I found the solution to my problem.
我相信我找到了解决问题的方法。
# -*- mode: python -*-
a = Analysis(['AMOS_Visualizer.py'],
pathex=['C:\Users\elu\PycharmProjects\Prosjektet\Forsok splitting'],
hiddenimports=[],
hookspath=None,
runtime_hooks=None)
for d in a.datas:
if 'pyconfig' in d[0]:
a.datas.remove(d)
break
a.datas += [('Logo.png','C:\Users\elu\PycharmProjects\Prosjektet\Forsok splitting\Logo.png', 'Data')]
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='AMOS_Visualizer.exe',
debug=False,
strip=None,
upx=True,
console=True, icon='C:\Users\elu\PycharmProjects\Prosjektet\Forsok splitting\AMOS.ico')
And adding the following to my main.py script
并将以下内容添加到我的 main.py 脚本中
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
Logo = resource_path("Logo.png")
回答by 2diabolos.com
This is a variation of the following: Bundling data files with PyInstaller (--onefile), and the given answer is clearer.
这是以下内容的变体: Bundling data files with PyInstaller (--onefile),给出的答案更清晰。
In 2 lines:
在 2 行中:
- You have to add your image files in "datas" (either in your spec files or with a PyInstaller hook script)
- Use the sys._MEIPASS if it
exists,
using the single linebase_path = getattr(sys, '_MEIPASS', '.')+'/'
to get a "root_path" variable to concatenation to all your files' paths.
Then,filepath = base_path + filepath
- 您必须在“数据”中添加您的图像文件(在您的规范文件中或使用 PyInstaller 挂钩脚本)
- 使用 sys._MEIPASS(如果存在),
使用单行base_path = getattr(sys, '_MEIPASS', '.')+'/'
获取“root_path”变量以连接到所有文件的路径。
然后,filepath = base_path + filepath
回答by Diego
If you are using Qt Designer you can do it by creating an resource file and adding all images you want, including the Logo.png, to this resource.
如果您使用 Qt Designer,您可以通过创建资源文件并将所需的所有图像(包括 Logo.png)添加到该资源中来实现。
To create a resource file you can follow the steps in Inserting an image in GUI using QT Designer.
要创建资源文件,您可以按照使用 QT 设计器在 GUI中插入图像中的步骤进行操作。
After you have inserted the images in the resource file, assign the Logo.png to the Window icon, save the QtDesigner interface and convert the resource file using the command: pyrcc4 -py3 resourcetest.qrc -o resourcetest_rc.py
在资源文件中插入图像后,将 Logo.png 分配给 Window 图标,保存 QtDesigner 界面并使用命令转换资源文件: pyrcc4 -py3 resourcetest.qrc -o resourcetest_rc.py
Finally, use --onefile option to create the exe file. No need to edit the spec file.
最后,使用 --onefile 选项创建 exe 文件。无需编辑规范文件。
回答by Aravind S
Add "datas = ['Location of your file']," before "hiddenimports = []". It will do. In my case this worked
在“hiddenimports = []”之前添加“datas = ['Location of your file']”。它会做。在我的情况下,这有效
# -*- mode: python -*-
block_cipher = None
a = Analysis(['embed.py'],
pathex=['C:\Users\Aravind\Desktop\exe'],
binaries=[],
datas=['C:\Users\Aravind\Desktop\exe\dist\map.png'],
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='embed',
debug=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=True )
回答by Michael Larsson
I have tried a lot but this worked after an hour:
我已经尝试了很多,但这在一个小时后起作用了:
When I run my programfile MilaBild.py the first time with:
当我第一次运行我的程序文件 MilaBild.py 时:
pyinstaller -F -w MilaBild.py
it seams to create the ".spec" file that I need to add the following to as stated in other coments above:
它接缝创建“.spec”文件,我需要将以下内容添加到上面的其他评论中:
a.datas += [('rosa.png','C:\Python34\rosa.png', 'DATA')]
the name of my imagefile is rosa.png. It is lokated at the same directory as my programfile MilaBild.py.
我的图像文件的名称是 rosa.png。它与我的程序文件 MilaBild.py 位于同一目录中。
I then allso had to add the part above as mentioned in coment above in my actuall program file:
然后我也不得不在我的实际程序文件中添加上面提到的部分:
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
Then I added in the part that gets the file to a variable and it worked:
然后我添加了将文件获取到变量的部分,它起作用了:
rosa = resource_path("rosa.png")
I tryed a lot and only to make this work took me one hour. Later I will try to make it with two images, sounds and subdirectories. But for now it it is 23:45 a'clock and that will be Another day, I feel very happy with this soo far, great break trough for me.
我尝试了很多,但只花了我一个小时才完成这项工作。稍后我将尝试使用两个图像、声音和子目录来制作它。但现在是凌晨 23 点 45 分,那将是另一天,到目前为止,我对这对我来说是一个很好的突破感到非常高兴。
回答by Le Droid
Finally it's simpler than what I found on various web pages & here.
最后它比我在各种网页和这里找到的更简单。
1) You specify in your code the relative path in temporary directory when the code is run as a compiled executable:
1)当代码作为编译的可执行文件运行时,您在代码中指定临时目录中的相对路径:
if getattr(sys, 'frozen', False): # Running as compiled
running_dir = sys._MEIPASS + "/files/" # Same path name than pyinstaller option
else:
running_dir = "./" # Path name when run with Python interpreter
iconFileName = running_dir + "mylogo.ico"
if os.path.isfile(iconFileName):
root.iconbitmap(iconFileName) # Exemple for tkinter usage
2) You give the path in the temporary directory created where your files will be stored on the compiler option:
2)您在创建的临时目录中提供路径,您的文件将存储在编译器选项中:
pyinstaller --onefile --add-binary "mylogo.ico;files" -i mylogo.ico myMainPrg.py
This way, you don't have to know the complete path where your files are in development and where you are going to install them in production.
这样,您就不必知道文件在开发中的完整路径以及将在生产中安装它们的位置。
回答by Mohd Fayeem
Nothings Worries. I've the same problem and got an answer by just doing this... Copy all my Images and paste them in dist/ and build/ directory created by pyinstaller, and problem solved. :)
没什么好担心的。我遇到了同样的问题,并通过这样做得到了答案......复制我所有的图像并将它们粘贴到由 pyinstaller 创建的 dist/ 和 build/ 目录中,问题解决了。:)