问题描述
我有一个程序和几个我在程序中使用的照片。
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与程序位于同一个文件夹中。
有没有办法把pics放在程序中? (虽然它们只是在文件夹中,但它们可以轻松更改或删除,我不希望它发生)
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)
可能是这样的:
k=b'bytes of pic here'
self.label_6.setPixmap(QtGui.QPixmap(k))
或任何其他方法。
我正在使用py2exe构建可执行文件(但即使选项'压缩':真 - 我的2个图片只是在文件夹中。他们不想去exe文件的INSIDE)。也许有办法让它们从文件夹中消失并进入程序。
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。
推荐答案
Qt正在使用系统完成这项任务。 pyqt也支持这一点。这里有一些关于SO的答案:和
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:
首先,创建一个资源文件(例如resources.qrc)。
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>
然后将资源文件编译成python模块:
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_())
这假定以下文件结构:
|-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
这篇关于python 3如何将pics放入我的程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!