在开发pythonQT的时候,打包成mac的dmg,遇到添加资源文件的路径问题,这里列出了我的解决办法。

首先看看如下代码:

#设置样式
def setCommonQPushButtonStyle(button, width=60, height=60, is_icon=False,fontSize=18, style = None):
    button.setFixedHeight(height)
    button.setFixedWidth(width)
    if not style:
        button.setStyleSheet( f"border:0;font-size: {fontSize}px;")
    else:
        button.setStyleSheet(style)
    # self.settings_button.setStyleSheet("background-color: green; color: white;")    
#获取根目录    
# 获取当前文件的绝对路径    
current_file_path = os.path.abspath(__file__)
    print("Project root directory:", current_file_path)
    # 获取项目根目录    
project_root = os.path.dirname(os.path.dirname(current_file_path))
    print("Project root directory:", project_root)
    if is_icon:
        button.setIconSize(QSize(40, 40))  # 设置图标大小 
        button.setIcon(QIcon('./assets/background.png'))
    return button

这里是抽象了一个设置QButton 样式的函数,代码中QIcon 设置的路径 直接就是图片的相对路径,我们在开放中调试的时候是没有问题的,但是打包后,就无法访问了。so 我们有pyrcc5来解决,将图片生成二进制文件,再引入使用。

1、资源存放地址如图:

在assets中新建icon.qrc文件,并引入

<RCC> 
<qresource prefix="pic"> 
<file>background.png</file> 
<file>loading.gif</file> 
</qresource>
</RCC>

prefix是引用前缀,可自定义,ok,我们运行命令如下(我是根目录运行):

pyrcc5 ./assets/icon.qrc -o ./icon.py

此时根目录生成了一个icon.py 文件,如下图:

引用使用,我们回到上面的函数片段,现将icon.py 文件导入,再将引用地址修改为以pic前缀的图片资源地址,修改后代码如下:


import os

from PyQt5.QtCore import QSize
from PyQt5.QtGui import QIcon
#引入icon.py 文件
import  icon

#设置样式
def setCommonQPushButtonStyle(button, width=60, height=60, is_icon=False,fontSize=18, style = None):
    button.setFixedHeight(height)
    button.setFixedWidth(width)
    if not style:
        button.setStyleSheet( f"border:0;font-size: {fontSize}px;")
    else:
        button.setStyleSheet(style)
    # self.settings_button.setStyleSheet("background-color: green; color: white;")
    #获取根目录
    # 获取当前文件的绝对路径
    current_file_path = os.path.abspath(__file__)
    print("Project root directory:", current_file_path)
    # 获取项目根目录
    project_root = os.path.dirname(os.path.dirname(current_file_path))
    print("Project root directory:", project_root)
    if is_icon:
        button.setIconSize(QSize(40, 40))  # 设置图标大小
        #修改资源地址
        button.setIcon(QIcon(':/pic/background.png'))
    return button

ok 这样就完成了,资源的引用,这样就不用去考虑图片的路径问题,打包后能看到图片资源了。。。。。

👆🏻👆🏻👆🏻扫码关注👆🏻👆🏻👆🏻

▼点个「」赞,是我持续更新的动力 

博客地址:blog.codeceo.net