python logo

pyqt display image


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

In this article we will demonstrate how to load and display images in an PyQT window. We can display images in a PyQT window using the Pixmap widget.

PyQt4-load-image An image loaded in a PyQt4 window.

Related course:

Introduction


The constructor of Pixmap takes the image path as parameter:

pixmap = QPixmap(os.getcwd() + '/logo.png')

This image needs to be in the same directory as your program. The QPixmap widget supports png and jpeg.  Example code below.

PyQT load image in Pixmap


We create a standard QWidget as we have done before. Then we add the QPixmap widget inside which will load the image. The Pixmap is attached to a label which is drawn to the screen.

import os
import sys
from PyQt4.QtGui import *

# Create window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle("PyQT4 Pixmap @ pythonspot.com ")

# Create widget
label = QLabel(w)
pixmap = QPixmap(os.getcwd() + '/logo.png')
label.setPixmap(pixmap)
w.resize(pixmap.width(),pixmap.height())

# Draw window
w.show()
app.exec_()

Download PyQT Code (Bulk Collection)

Result:

pyqt Pixmap pyqt Pixmap

BackNext





Leave a Reply:




Jeremy Lee Sat, 23 May 2015

At least on Windows - this hangs without response to ^C if logo does not exist.
Added simple error check


import os
import sys
from PyQt4.QtGui import *
# Create window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle("PyQT4 Pixmap @ pythonspot.com ")
# Create widget
label = QLabel(w)
picfile='logo.png'
logo = os.getcwd() + '\\' + picfile
print logo
if os.path.isfile(logo):
pixmap = QPixmap(logo)
label.setPixmap(pixmap)
w.resize(pixmap.width(),pixmap.height())
# Draw window
w.show()
app.exec_()
else:
print "I expected to find a png picture called logo.png in "+ os.getcwd()

Frank Sat, 23 May 2015

Hi Jeremy, after changing to the correct quotes and changing the \\ to /, this program works fine under Linux.
Did you try with other image formats such as JPG or GIF? Make sure the quotes are correct.