How to add an image to the PyQt5 window
PyQt5 module is used to create GUI applications.
We will learn to add an image to the PyQt5 window in this shot.
Prerequisites
- Download & Install latest Python version.
- Install
PyQt5module with pip.
pip install pyqt5
Implementation
- Load the image with
QPixmap(), which will accept the image path as a parameter and returns an instance ofQPixmap.
pixmap = QPixmap('nature.png')
- Attach
Qpixmapinstance to label.
label.setPixmap(pixmap)
The following code snippet will create a PyQt5 window and load an image on it:
- Line 6: Create a
Windowclass. - Line 13: Set
windowtitle. It will be displayed on top of thewindow. - Line 16: Set Geometry, It will set the
windowsize, here the width is500and height is500. - Line 19: Create an instance of
QLabeland assign it to the label variable. - Line 22: Create an instance of
QPixmap(), by passing the image path as a parameter and assigning the instance topixmap. - Line 25: Set
pixmapto label.
from PyQt5.QtWidgets import *from PyQt5.QtGui import QPixmapimport sysclass Window(QMainWindow):def __init__(self):super().__init__()self.acceptDrops()# set window titleself.setWindowTitle("Load Image on Window")# set window sizeself.setGeometry(0, 0, 500, 500)# Create an instance of labelself.label = QLabel(self)# Load imageself.pixmap = QPixmap('nature.png')# Set image to labelself.label.setPixmap(self.pixmap)# Resize the label according to image sizeself.label.resize(self.pixmap.width(),self.pixmap.height())# show the widgetsself.show()# Instantiate pyqt5 applicationApp = QApplication(sys.argv)# create window instancewindow = Window()# start the appsys.exit(App.exec())