You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code直接打开文件与文件夹时PyQt6图片不显示问题

PyQt6样式表中图片路径在单独运行/打包后不显示的解决方法

问题根源

  1. 单独打开main.py或打包成exe后,程序的工作目录不是脚本/可执行文件所在目录,导致相对路径image.jpg无法定位到图片。
  2. PyQt样式表对本地路径的解析规则和QPixmap不同:直接传入带反斜杠的系统绝对路径时,反斜杠会被当成转义字符,导致路径识别失败。

正确解决代码

方法1:用QUrl转换为file协议格式(推荐)

import os
from PyQt6.QtCore import QUrl

# 获取当前脚本/可执行文件的绝对目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接图片绝对路径
image_path = os.path.join(current_dir, 'image.jpg')
# 转换为PyQt样式表可识别的file:///协议格式
url = QUrl.fromLocalFile(image_path).toString()
# 应用到样式表
self.ui.label.setStyleSheet(f"border-image: url({url}); border-top-left-radius: 50px;")

方法2:手动替换路径中的反斜杠为正斜杠

import os

current_dir = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(current_dir, 'image.jpg').replace("\\", "/")
self.ui.label.setStyleSheet(f"border-image: url({image_path}); border-top-left-radius: 50px;")

PyInstaller打包补充

打包时需要确保图片被正确复制到输出目录,添加以下参数:

  • Windows系统:pyinstaller --add-data "image.jpg;." main.py
  • Linux/macOS系统:pyinstaller --add-data "image.jpg:." main.py

内容的提问来源于stack exchange,提问作者dumbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 10:30:08