如何使用Python在单个Tkinter画布中显示来自多个URL的多个图像

时间:2017-02-04 09:04:35

标签: python canvas tkinter web-scraping tkinter-canvas

我有一个url列表,每个url只包含一个图像,我想使用python在单个tkinter画布上显示所有图像,列表中包含一些不包含图像的url tkinter应该忽略那些网址。

我创建的代码一次只能显示一个图像。

import io
import base64
try:
    # Python2
    import Tkinter as tk
    from urllib2 import urlopen
except ImportError:
    # Python3
    import tkinter as tk
    from urllib.request import urlopen
root = tk.Tk()
root.title("display a website image")

w = 800
h = 600
x = 200
y = 300

root.geometry("%dx%d+%d+%d" % (w, h, x, y))


image_url = "http://www.okclipart.com/img2/yrdulrdklckodbfcqsuy.png"
image_byt = urlopen(image_url).read()
image_b64 = base64.encodestring(image_byt)
photo = tk.PhotoImage(data=image_b64)

cv = tk.Canvas(bg='white')
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(10, 10, image=photo, anchor='nw')
root.mainloop()

图片样本列表网址

urllist =['https://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/NoCopyright.png/600px-NoCopyright.png','http://www.okclipart.com/img16/kjlhjznjvkokwqpalupl.png'
,'http://www.okclipart.com/img16/qcmwejvtwuufltxsibbn.png',
'http://www.okclipart.com/img2/yrdulrdklckodbfcqsuy.png']

此外,列表中还有一些不包含任何图像的网址,因此它会忽略这些网址。

1 个答案:

答案 0 :(得分:2)

  1. 忽略无效网址try ... except urllib2.HTTPError将为您提供帮助
  2. 加载多张图片:浏览urllist并加载每张图片。成功后,将其绘制到画布上。
  3. #from urllib.request import HTTPError #py3
    #from urllib2 import HTTPError #py2
    #... 
    def load_image_to_base64(image_url):
        """ Load an image from a web url and return its data base64 encoded"""
        image_byt = urlopen(image_url).read()
        image_b64 = base64.encodestring(image_byt)
        return image_b64
    
    # load photos to photos list
    urllist = ['http://www.okclipart.com/img16/kjlhjznjvkokwqpalupl.png', 
               'invalidurltest', 
               'http://www.okclipart.com/YouWontFindThisImage.png']
    photos = []
    for i, url in enumerate(urllist):
        print(i,"loading",url)
        try:
            photo = tk.PhotoImage(data=load_image_to_base64(url))
            photos.append(photo)
            print("done")
        except HTTPError as err:
            print("image not found, http error code:", err.code)
        except ValueError:
            print("invalid url", url)
    
    # iterate through photos and put them onto the canvas
    for photo in photos:
        cv.create_image(10*i, 10*i, image=photo, anchor='nw')
    
    root.mainloop()
    #...