Python PyInstaller and include window icon
Asked Answered
A

3

7

I have set the icon for my PyQt application using self.setWindowIcon(QtGui.QIcon('icon.png')) and it works fine when I run my code in PyCharm.

Next I converted my application to one file with PyInstaller:

pyinstaller.exe --onefile --windowed opc.py --name myapps

However, when running the executable the icon is not shown. What am I doing wrong ?


On left site code from PyCharm, on right site from one file (pyinstaller.exe --onefile --windowed opc.py --name myapps). Why is not the same ? I want .png icon because is transparent.

Icon comparison

Abm answered 19/5, 2016 at 11:14 Comment(0)
M
5

The icon displayed when running an executable on Windows comes from the executable file itself. To bundle an icon with your application you need to specify the icon when building with pyinstaller.exe by passing the --icon parameter. For example:

pyinstaller.exe --onefile --windowed --name myapps --icon=icon.ico opc.py

Note that unlike for setWindowIcon() the icon file must be in .ico format, so you will need to convert it from the .png first.

If you want to use the PyQt call to set the icon you will need to bundle the icon file into the executable, which can be done using a PyInstaller spec file. A walkthrough of the process of creating and modifying the spec file is in this previous answer.

Mewl answered 19/5, 2016 at 11:23 Comment(2)
It's not that what I wanted. I updated my question and added photo.Abm
@Abm see the edit above. You will need to bundle the .png file into the executable to achieve what you want. The linked answer should do the trick.Mewl
M
1

I solve the problem in the following way

I invoke the resource within the code:

class MainWindow(QMainWindow):
    def __init__(self):
        icon_path = os.path.join(sys._MEIPASS, 'icon.ico')
        self.setWindowIcon(QIcon(icon_path))

sys._MEIPASS allows you to access temporary files generated during the program's execution

I add the resource in the executable:

$python -m PyInstaller --onefile --noconsole --icon=icon.ico --add-data "icon.ico;." main.py
Metrist answered 4/8, 2023 at 9:37 Comment(0)
C
0

To have compatibility in both .py and .exe you can do this:

if getattr(sys, 'frozen', False):
    applicationPath = sys._MEIPASS
elif __file__:
    applicationPath = os.path.dirname(__file__)
app = QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon(os.path.join(applicationPath, "Icon.ico")))

And for your pyinstaller call:

pyinstaller --icon=Icon.ico --add-data="Icon.ico;." "main.py"
Chorion answered 21/3 at 9:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.