问题
I have a program and couple of pics which I use in the program.
icon.addPixmap(QtGui.QPixmap("logo_p3.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.label_6.setPixmap(QtGui.QPixmap("Logo-4.jpg"))
Pics are in the same folder with the program. Is there any way to put pics INSIDE the program? (While they are just in the folder they can be easily changed or deleted, and I don't want it to happen)
May be something like this:
k=b'bytes of pic here'
self.label_6.setPixmap(QtGui.QPixmap(k))
or any other method.
I'm using py2exe to build executables (but even with option 'compressed': True - my 2 pics are just in the folder. They don't want to go INSIDE of exe file). Maybe there is a way to make them disappear from the folder and go inside to the program.
Thanx.
回答1:
Qt is using a resource system for this task. This is also supported by pyqt. There are a few answers here on SO already: here and here
Here is a quick example:
First, create a resource file (e.g., resources.qrc).
<!DOCTYPE RCC><RCC version="1.0">
<qresource prefix="/images">
<file alias="image.png">images/image.png</file>
</qresource>
</RCC>
Then compile the resource file into a python module:
pyrcc5 -o resources_rc.py resources.qrc
Then include the resource file and when you create a pixmap, use the resource notation.
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLabel
from PyQt5.QtGui import QPixmap
import resources_rc
class Form(QWidget):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
mainLayout = QGridLayout()
pixmap = QPixmap(':/images/image.png') # resource path starts with ':'
label = QLabel()
label.setPixmap(pixmap)
mainLayout.addWidget(label, 0, 0)
self.setLayout(mainLayout)
self.setWindowTitle("Hello Qt")
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
screen = Form()
screen.show()
sys.exit(app.exec_())
This assumes the following file structure:
|-main.py # main module
|-resources.qrc # the resource xml file
|-resouces_rc.py # generated resource file
|-images # folder with images
|--images/image.png # the image to load
来源:https://stackoverflow.com/questions/30047692/python-3-how-to-put-pics-inside-my-program