在tkinter中显示来自url的图像

时间:2016-07-03 19:19:11

标签: python tkinter python-3.5

正如标题所说,我想从网址显示图片,而不下载。到目前为止我的代码:

from bs4 import BeautifulSoup as soup
from tkinter import *
import urllib.parse
from PIL import Image, ImageTk
import io

website = "http://www.porcys.com/review/"
openWebsite = soup(urllib.request.urlopen(website), 'html.parser')

reviews = openWebsite.find(name="section", attrs={'class': 'slider-content review'}).ul

results = []
for a in reviews(href=True):
    temp = "http://www.porcys.com"+a['href']
    results.append(temp)

mainWindow = Tk()
mainWindow.title("Latest Porcys reviews")

for i in range(0, 8):
    review = results[i]
    openReview = soup(urllib.request.urlopen(review), 'html.parser')
    rating = openReview.find(name="span", attrs={'class': 'rating'})
    album = openReview.find(name="div", attrs={'class': 'wrapper'}).i
    artist = openReview.find(name="div", attrs={'class': 'wrapper'}).h2
    coverWIP = openReview.find(name="img", attrs={'class': 'cover'})
    for tag in openReview.find_all('i'):
        tag.replaceWith(' ')
    print(artist.text)
    print(album.text)
    print(rating.text)
    cover = "http://www.porcys.com"+coverWIP['src']
    print(cover)
    artistAndAlbum = Label(font=("Helvetica",10), text=artist.text+'- '+album.text)
    artistAndAlbum.grid(row=i, column=100, sticky=W)
    ratingGUI = Label(font=("Helvetica",10), text=rating.text)
    ratingGUI.grid(row=i+1,columnspan=100)
    raw_data = urllib.request.urlopen(cover).read()
    im = Image.open(io.BytesIO(raw_data))
    image = ImageTk.PhotoImage(im)
    label1 = Label(mainWindow, image=image)
    label1.grid(row=i, sticky=W)
    mainWindow.mainloop()

" mainWindow.mainloop()"导致麻烦 - 当在循环内部时,它只显示第一张图像,关闭寡妇后,会抛出一些错误。当我把它放在循环外面时,它只显示最后一张图像。此外,我不确定它是否是显示图像的最有效方式。

1 个答案:

答案 0 :(得分:2)

http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm 提供了解释。

  

将PhotoImage或其他Image对象添加到Tkinter小部件时,   你必须保持自己对图像对象的引用。如果你不这样做,   图像不会一直显示出来。

     

问题是Tkinter / Tk接口不处理引用   到图像对象正确; Tk小部件将保存对该引用的引用   内部对象,但Tkinter没有。

所以像这样,

images = []

for i in range(0, 8):
    ...
    raw_data = urllib.request.urlopen(cover).read()
    im = Image.open(io.BytesIO(raw_data))
    image = ImageTk.PhotoImage(im)
    label1 = Label(mainWindow, image=image)
    label1.grid(row=i, sticky=W)

    # append to list in order to keep the reference
    images.append(image)
mainWindow.mainloop()