简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM