Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
pyqt5
communitycreator

How to add an image to the PyQt5 window

Gutha Vamsi Krishna

PyQt5 module is used to create GUI applications.

We will learn to add an image to the PyQt5 window in this shot.

Prerequisites

pip install pyqt5

Implementation

  • Load the image with QPixmap(), which will accept the image path as a parameter and returns an instance of QPixmap.
pixmap = QPixmap('nature.png')
  • Attach Qpixmap instance to label.
label.setPixmap(pixmap)

The following code snippet will create a PyQt5 window and load an image on it:

  • Line 6: Create a Window class.
  • Line 13: Set window title. It will be displayed on top of the window.
  • Line 16: Set Geometry, It will set the window size, here the width is 500 and height is 500.
  • Line 19: Create an instance of QLabel and 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 to pixmap.
  • Line 25: Set pixmap to label.
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
import sys


class Window(QMainWindow):
	def __init__(self):
		super().__init__()

		self.acceptDrops()

		# set window title
		self.setWindowTitle("Load Image on Window")

		# set window size
		self.setGeometry(0, 0, 500, 500)

		# Create an instance of label
		self.label = QLabel(self)
		
		# Load image
		self.pixmap = QPixmap('nature.png')

		# Set image to label
		self.label.setPixmap(self.pixmap)

        # Resize the label according to image size
		self.label.resize(self.pixmap.width(),
						self.pixmap.height())

		# show the widgets
		self.show()

# Instantiate pyqt5 application
App = QApplication(sys.argv)

# create window instance
window = Window()

# start the app
sys.exit(App.exec())

Output

widget

RELATED TAGS

python
pyqt5
communitycreator
RELATED COURSES

View all Courses

Keep Exploring