How to add a photo to pyqt5 to convert to exe format
I use a qt5 graphical editor for python. I need to add a photo like background
. But I ran into a problem when using the usual label
with the file path, when converting the file to exe format using pyinstalle
r, the photo is simply not there.
I remember that it was possible to do this somehow via qrc
, but I write the code manually and do not know how to implement it correctly. Here is what the lines on label
look like. +++ this is in the widget class. The file resource is there. All in the root.
import resources
pixmap = QPixmap("ZeXsPua_AKU.png")
2 answers
You need to add a resource file to the project. for example , resources.qrc
<RCC>
<qresource prefix="newPrefix">
<file>picture.png</file>
</qresource>
</RCC>
Which then you need to convert pyrcc5 -o resources.py resources.qrc
and use in this form
import resources
...
pixmap = QPixmap(":/newPrefix/picture.png")
You can write in the comments for a long time. For simplicity, let's do this. the simplest example.
I have in one directory are: test.py, image.png, resources.qrc the program itself test.py
import sys
from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QLabel, QApplication)
from PyQt5.QtGui import QPixmap
import resources
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
pixmap = QPixmap(":/newPrefix/image.png")
lbl = QLabel(self)
lbl.setPixmap(pixmap)
hbox.addWidget(lbl)
self.setLayout(hbox)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
The resources file.qrc of this type:
<RCC>
<qresource prefix="newPrefix">
<file>image.png</file>
</qresource>
</RCC>
To start, run pyrcc5 -o resources.py resources.qrc
and get the module in the same directory resources.py
Now I can make an exe and transfer it to another computer: pyinstaller --onefile test.py