Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt4 and Python 3 - Display an image from URL

I found this code for displaying image from URL. This code doesn't work with Python 3.4. I think urllib is seperated two modules on Python 3 as urllib.request. But I can't convert this code to display it on Python 3.

from PyQt4.QtGui import QPixmap, QIcon
import urllib

url = 'http://example.com/image.png'    
data = urllib.urlopen(url).read()
pixmap = QPixmap()
pixmap.loadFromData(data)
icon = QIcon(pixmap)

So how can I display image on Python 3 and Pyqt4? Thanks.

like image 425
Rictrunks Avatar asked Dec 26 '22 08:12

Rictrunks


1 Answers

Try this:

import sys
from PyQt4 import QtGui
import urllib.request

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):
        hbox = QtGui.QHBoxLayout(self)

        url = 'http://www.google.com/images/srpr/logo1w.png'
        data = urllib.request.urlopen(url).read()

        image = QtGui.QImage()
        image.loadFromData(data)

        lbl = QtGui.QLabel(self)
        lbl.setPixmap(QtGui.QPixmap(image))

        hbox.addWidget(lbl)
        self.setLayout(hbox)

        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
like image 197
NorthCat Avatar answered Dec 31 '22 12:12

NorthCat