【问题标题】:Icons missing from PyQt5 app after compiling to .exe using pyinstaller使用 pyinstaller 编译为 .exe 后,PyQt5 应用程序中缺少图标
【发布时间】:2019-03-10 07:45:13
【问题描述】:

已解决 - 解决方案已作为答案发布,感谢大家的帮助。

使用PyQt5 将我的python 应用程序编译为可执行文件后,我的GUI 中包含的图标将被删除/不显示。 具体来说,QIcon 实例使用 self.setWindowIcon(QtGui.QIcon(fpath)) 添加到我的 Window(QMainWindow) 类中,QPixmap(f2path) 通过 label.setPixmap(myPixmap) 嵌入到 QLabel 中。

我尝试在此论坛上搜索可能的解决方案,但找不到解决问题的线程。 我尝试按照此处Bundling data files with PyInstaller (--onefile) 和此处Missing button icons in pyinstaller 的建议设置绝对文件路径

不知道从哪里开始检查问题,使用pyinstaller 编译时没有错误,并且作为 python 脚本运行良好。

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())

【问题讨论】:

  • 我已经尝试了 3 次在顶部添加一个友好的“你好”,但不起作用..
  • 提供minimal reproducible example。如何添加图标?您是使用相对路径还是绝对路径,还是使用 qresource?
  • @MalteHerrmann 请参阅meta.stackoverflow.com/q/251077/1288408
  • @ModusTollens 谢谢,很高兴知道!这里有新的...
  • @a_guest 谢谢!在.spec-文件中将图像指定为附加数据解决了我的问题!

标签: python python-3.x pyqt pyqt5 pyinstaller


【解决方案1】:

解决方案是专门将图像文件添加到.spec 文件中,然后使用生成.exe 文件

$> pyinstaller myGUI.spec

这是.spec文件的相关部分:

a = Analysis(['myGUI.py'],
     ...,
     datas = [('myIcon.png', '.')],
     ...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多