PyQt5——打包资源文件

打包资源文件

使用PyQt5生成的应用程序引用图片资源的主要方法有两种

  • 第一种方法:将资源转换为Python文件,然后引用Python文件

  • 第二种方法:在程序中通过相对路径引用外部图片资源

使用Qt Designer 加载资源文件

在Qt Designer中设计界面时是不能直接加入图片或图标资源的,而是需要在PyQt5开发目录下编辑.qrc文件

新建一个资源文件apprcc.qrc

<rcc version="1.0">
    <qresource>

    </qresource>
</rcc>

打开Qt Desinger新建一个Widget的简单窗体,命名为MainWin02,然后打开资源管理器
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

查看apprcc.qrc文件

<RCC>
  <qresource prefix="pic">
    <file>images/cartoon1.ico</file>
    <file>images/cartoon2.ico</file>
    <file>images/cartoon3.ico</file>
    <file>images/cartoon4.ico</file>
    <file>images/python.jpg</file>
  </qresource>
</RCC>

在窗体中使用资源文件

使用Qt Designer在窗体中放置控件

选择Label控件拖放在Form中间按并选中它,然后在Qt Desinger窗口右侧的属性编辑器找到pixmap属性
在这里插入图片描述

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(684, 472)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(123, 101, 491, 321))
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap(":/pic/images/python.jpg"))
        self.label.setObjectName("label")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
import apprcc_rc

转换后的Python文件,但是apprcc_rc 找不到,说明需要将apprcc_rc转化为python文件

转换资源文件

apparc.qrc转换为apprcc_rc.py文件

pyrcc5 apprcc.qrc -o apprcc_rc.py

在这里插入图片描述

其中部分的内容

调用

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from MainWin02 import Ui_Form
class MyMainWindow(QMainWindow, Ui_Form):
    def __init__(self, parent = None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWin = MyMainWindow()
    myWin.show()
    sys.exit(app.exec_())

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值