Tech With Tim Logo
Go back


This PyQt5 tutorial will show you how to display images using something called a QPixmap.

Displaying an Image

For this tutorial we will create an image using PyQt Designer and then change them image source from our python code.

To display an image we can actually use a label!

We will start by dragging in a label and resizing it to our desired dimensions. After that we will scroll all the way down in the Property Editor tab until we see a property that says Pixmap. Here we can select an image file to display. kuva_2023-04-20_141430470.png

After clicking the black arrow we can select a file.

Changing the Image

For this specific program I'd like to create two buttons that we can use to change the image. I've set up my UI to support this by adding two buttons. kuva_2023-04-20_141458210.png

After you create your UI save it and convert it to a python file using the following command:

pyuic5 -x "filename".ui -o "filename".py

Next we will open our python file and add some methods to change the image source.

To edit our image source we will use the following line."dog.jpg"))
# note: photo is the name of my label
# "dog.jpg" is a photo that is in the same directory as my python file

We'll add some methods that we can call to change the image.

    def show_cat(self):"cat.jpg"))
    def show_dog(self):"dog.jpg"))

And finally link our buttons to call them.

    def setupUI(self):

Full Code

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'test.ui'
# Created by: PyQt5 UI code generator 5.11.3
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget") = QtWidgets.QLabel(self.centralwidget), 0, 841, 511))"")"cat.jpg"))"photo") = QtWidgets.QPushButton(self.centralwidget), 510, 411, 41))"cat") = QtWidgets.QPushButton(self.centralwidget), 510, 391, 41))"dog")
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.statusbar = QtWidgets.QStatusBar(MainWindow)


    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))"MainWindow", "CAT"))"MainWindow", "DOG"))

    def show_dog(self):"imgs/dog.jpg"))

    def show_cat(self):"imgs/cat.jpg"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
Design & Development by Ibezio Logo