您现在的位置是:网站首页 > 博客日记 >

Pyside2让gif动起来

作者:YXN-python 阅读量:14 发布日期:2024-11-05

import sys
from PySide2.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
from PySide2.QtGui import QMovie, QIcon
from PySide2.QtCore import QSize, QTimer


class CircularRefreshButton(QPushButton):
    def __init__(self, gif_path, parent=None):
        super().__init__(parent)

        # 初始化 QMovie
        self.movie = QMovie(gif_path)
        self.movie.setScaledSize(QSize(100, 100))  # 调整大小
        self.movie.jumpToFrame(0)  # 显示第一帧

        # 设置初始图标为第一帧
        self.setIcon(QIcon(self.movie.currentPixmap()))
        self.setIconSize(QSize(100, 100))
        self.setFixedSize(100, 100)
        self.setStyleSheet("QPushButton {border-radius: 50px;}")

        # 连接 QMovie 帧变化信号到更新按钮图标的槽
        self.movie.frameChanged.connect(lambda: self.setIcon(QIcon(self.movie.currentPixmap())))

        # 点击后启动动画
        self.clicked.connect(self.start_animation)

    def start_animation(self):
        self.movie.start()
        # 3秒后停止gif
        QTimer.singleShot(3000, self.stop_animation)

    def stop_animation(self):
        self.movie.stop()
        self.movie.jumpToFrame(0)  # 停止后显示回到第一帧
        self.setIcon(QIcon(self.movie.currentPixmap()))


if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 创建主窗口
    window = QWidget()
    layout = QVBoxLayout(window)

    button = CircularRefreshButton("../../img/up.gif")
    layout.addWidget(button)

    window.show()
    sys.exit(app.exec_())

YXN-python

2024-11-05