PyQt5 image


PyQt5 (and Qt) support images by default. In this article we’ll show you how to add an image to a window. An image can be loaded using the QPixmap class.

Related course:
PyQt Desktop Apps with Python

PyQt5 image introduction
Adding an image to a PyQt5 window is as simple as creating a label and adding an image to that label.

label = QLabel(self)
pixmap = QPixmap('image.jpeg')
label.setPixmap(pixmap)
 
# Optional, resize window to image size
self.resize(pixmap.width(),pixmap.height())

These are the required imports:

from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap

pyqt5 qpixmap

PyQt5 load image (QPixmap)

Copy the code below and run it. The image should be in the same directory as your program.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap
 
class App(QWidget):
 
def __init__(self):
super().__init__()
self.title = 'PyQt5 image - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
 
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
 
# Create widget
label = QLabel(self)
pixmap = QPixmap('image.jpeg')
label.setPixmap(pixmap)
self.resize(pixmap.width(),pixmap.height())
 
self.show()
 
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Back
Next

4 thoughts on “PyQt5 image

  1. Vijaya Bhaskar - March 11, 2018

    Hi Frank..
    I ran this program using MSDOS. There was no error. However there is no window displayed.
    How we execute this program on CMD so we can see the frame/dialogbox?

    1. Frank - March 11, 2018

      Is the image (image.jpeg) in the same directory as the Python program? After loading print pixmap.width() to make sure it’s loaded

  2. Hassan Tariq - June 21, 2017

    How can i pass a variable which contains file path in QPixmap,instead if directly passing the image name. if doing like this:

    image = QFileDialog.getOpenFileName(None,'OpenFile','C:\\',"Image file(*.png)")
    self.label.setPixmap(QPixmap(qimage)

    But it gives me an error QPixmap(): argument 1 has unexpected type ‘tuple’

    I have been struggling with it for quiet a few days. Please tell me what should i do.

    1. Frank - June 29, 2017

      It returns a tuple, the first parameter of the tuple contains the path and filename.
      Add these lines:

      image = QFileDialog.getOpenFileName(None,'OpenFile','',"Image file(*.png)")
      imagePath = image[0]
      pixmap = QPixmap(imagePath)
      label.setPixmap(pixmap)
      self.resize(pixmap.width(),pixmap.height())

Leave a Reply