Learn Python PyQt

PyQt show gif

PyQt can display (animated) Gifs using QMovie. In this article we will show you how to do that.

It is straightforward how to do that and you can display a multiple of gifs if you want to.

Book: Create Desktop Apps with Python PyQt5

Animated gif with PyQt

Import a GIF file using QMovie and display it on a label. QMovie is a class for playing movies, but it can also play (animated) gifs.

The program below displays an animated gif (earth.gif).
Screenshot is a frozen shot, but gif is animated and plays in the window.

pyqt animated gif

You can add the full path to the gif or have it in the same directory as your program.

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

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(250, 250)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # create label
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(25, 25, 200, 200))
        self.label.setMinimumSize(QtCore.QSize(200, 200))
        self.label.setMaximumSize(QtCore.QSize(200, 200))
        self.label.setObjectName("label")

        # add label to main window
        MainWindow.setCentralWidget(self.centralwidget)

        # set qmovie as label
        self.movie = QMovie("earth.gif")
        self.label.setMovie(self.movie)
        self.movie.start()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(window)
    window.show()
    sys.exit(app.exec_())

Code Analysis

Load the required modules

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QMovie

Set up your Python PyQt window

MainWindow.setObjectName("MainWindow")
MainWindow.resize(250, 250)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")

Create a label for the gif to be displayed in

# create label
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(25, 25, 200, 200))
self.label.setMinimumSize(QtCore.QSize(200, 200))
self.label.setMaximumSize(QtCore.QSize(200, 200))
self.label.setObjectName("label")

Add the label you created to the window

# add label to main window
MainWindow.setCentralWidget(self.centralwidget)

Then load the gif, add it to the label and play it

# set qmovie as label
self.movie = QMovie("earth.gif")
self.label.setMovie(self.movie)
self.movie.start()