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

Python脚本运行正常 打包为exe后GIF动图无法加载问题求助

问题原因

核心原因是资源路径定位错误,且打包时没有将GIF资源一同封装进exe文件:

  • 代码中使用QMovie("loader.gif")的相对路径加载资源,直接运行脚本时程序会从当前脚本所在目录检索loader.gif,因此可以正常加载播放
  • 使用--onefile模式打包后,exe运行时会先把所有内置资源解压到系统临时文件夹的随机目录下,你没有将loader.gif打包进exe,程序运行时默认从exe所在目录检索GIF文件,如果没有手动把GIF和exe放在同一目录就会加载失败;就算手动放置也不符合单文件便携的使用需求。

修复方案

步骤1:修改代码适配双场景资源路径

新增资源路径适配函数,兼容开发运行和打包运行两种场景的路径定位:

import sys
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QMovie
from PyQt5.QtCore import Qt

# 新增资源路径适配函数
def resource_path(relative_path):
    if getattr(sys, 'frozen', False):
        # 打包后运行时的临时资源目录
        base_path = sys._MEIPASS
    else:
        # 开发阶段脚本所在目录
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

class LoadingGif(object):

    def mainUI(self, FrontWindow):
        FrontWindow.setObjectName("FTwindow")
        FrontWindow.resize(320, 300)
        self.centralwidget = QtWidgets.QWidget(FrontWindow)
        self.centralwidget.setObjectName("main-widget")

        # Label Create
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(25, 25, 200, 200))
        self.label.setMinimumSize(QtCore.QSize(250, 250))
        self.label.setMaximumSize(QtCore.QSize(250, 250))
        self.label.setObjectName("lb1")
        FrontWindow.setCentralWidget(self.centralwidget)

        # 修改GIF加载逻辑,使用适配后的绝对路径
        self.movie = QMovie(resource_path("loader.gif"))
        self.label.setMovie(self.movie)

        self.startAnimation()

    # Start Animation

    def startAnimation(self):
        self.movie.start()

    # Stop Animation(According to need)
    def stopAnimation(self):
        self.movie.stop()


app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QMainWindow()
demo = LoadingGif()
demo.mainUI(window)
window.show()
sys.exit(app.exec_())

步骤2:修改打包命令,将GIF一同封装

执行打包时添加--add-data参数,指定要打包进exe的GIF资源:

  • Windows平台命令:
    pyinstaller --onefile --add-data "loader.gif;." abc.py
  • Mac/Linux平台命令:
    pyinstaller --onefile --add-data "loader.gif:." abc.py

打包完成后生成的单文件exe可以直接运行,无需额外携带GIF文件。


内容的提问来源于stack exchange,提问作者Ateeq Ur Rehman AU

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:36:04