使用 pyinstaller 编译为 .exe 后,PyQt5 应用程序中缺少图标 [英] Icons missing from PyQt5 app after compiling to .exe using pyinstaller
问题描述
已解决 - 作为答案发布的解决方案,感谢大家的帮助.
使用PyQt5
将我的python 应用程序编译为可执行文件后,GUI 中包含的图标被删除/不显示.特别是 QIcon
实例添加到我的 Window(QMainWindow)
类使用 self.setWindowIcon(QtGui.QIcon(fpath))
和一个 QPixmap(f2path)
通过 label.setPixmap(myPixmap)
嵌入到 QLabel
中.
After compiling my python application using PyQt5
to an executable file, the icons contained in my GUI are removed / not displayed.
Specifically QIcon
instances added to my Window(QMainWindow)
class using self.setWindowIcon(QtGui.QIcon(fpath))
and a QPixmap(f2path)
embedded in a QLabel
via label.setPixmap(myPixmap)
.
我尝试在此论坛上搜索可能的解决方案,但找不到解决问题的线程.我尝试按照此处的建议设置绝对文件路径 将数据文件与PyInstaller (--onefile) 和这里 pyinstaller 中缺少按钮图标
I have tried to search on this forum for possible solutions but couldn't find a problem solving thread. I've tried to set the absolute filepath as recommended here Bundling data files with PyInstaller (--onefile) and here Missing button icons in pyinstaller
不知道从哪里开始检查问题,使用 pyinstaller
编译时没有错误,并且它作为 python 脚本运行良好.
No idea where to start examining problems, there are no errors when compiling with pyinstaller
and it runs fine as a python script.
pyinstaller -w -F MY_GUI.py
提前致谢!
示例:
import sys
import os
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
<小时>
import sys
import resource_path # code taken from links above
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "MyProg"
self.top = 400
self.left = 400
self.width = 680
self.height = 540
icon_path = resource_path("icon.png")
self.setWindowIcon(QtGui.QIcon(icon_path))
self.InitUI()
def InitUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.show()
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
推荐答案
解决方案是将图片文件专门添加到.spec
文件中,然后生成.exe
使用
The solution was to specifically add the image files to the .spec
file then generate the .exe
file using
$> pyinstaller myGUI.spec
这是 .spec
文件的相关部分:
Here is the relevant part of the .spec
file:
a = Analysis(['myGUI.py'],
...,
datas = [('myIcon.png', '.')],
...)
这篇关于使用 pyinstaller 编译为 .exe 后,PyQt5 应用程序中缺少图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!