python logo

PyQt5 image

Python hosting: Host, run, and code Python in the cloud!

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:

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_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

BackNext





Leave a Reply:




Hassan Tariq Wed, 21 Jun 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.

Frank Thu, 29 Jun 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())