Python Forum

Full Version: Trouble displaying an image in PyQt4
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey guys, I am attempting to display an image with this setWindowIcon command. However, I am getting an error. Here is my attempt:

import sys
from PyQt4 import QtGui

class Window(QtGui.QMainWindow):
  def __init__(self):
    super(Window, self).__init__() #returns parent object (q main window object)
    self.setGeometry(50, 50, 500, 300)
    self.setWindowTitle("PyQt4 Window")

    with open('Logo.png') as f:
      pngdata = f.read()

    self.setWindowIcon(QtGui.QIcon(pngdata))
    self.show()

app = QtGui.QApplication(sys.argv)
GUI = Window()

sys.exit(app.exec_())
The error:

/usr/bin/python3 /home/rob/PycharmProjects/untitled/xcfgh.py
Traceback (most recent call last):
File "/home/rob/PycharmProjects/untitled/xcfgh.py", line 17, in <module>
GUI = Window()
File "/home/rob/PycharmProjects/untitled/xcfgh.py", line 11, in __init__
pngdata = f.read()
File "/usr/lib/python3.5/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

I am a bit confused. Why would I be getting a utf-8 error this is an image not a string. Should I not be using f.read()?
an image is binary data, so to read:
with open('Logo.png', 'rb') as f:
You can open the image as a QPixmap instead;
import sys
from PyQt4 import QtGui

class Window(QtGui.QMainWindow):
  def __init__(self):
    super(Window, self).__init__() #returns parent object (q main window object)
    self.setGeometry(50, 50, 500, 300)
    self.setWindowTitle("PyQt4 Window")

    pixmap = QtGui.QPixmap('/home/will/DATA/Images/12384249_501942289985392_374306926_n.gif')
    self.setWindowIcon(QtGui.QIcon(pixmap))
    self.show()

app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())