0

好吧,我彻底糊涂了。所以我最近开始使用 Steam API,我决定开始做一些简单的事情,显示个人资料的头像图像。

事情是,程序运行没有错误,只是它不显示图像。

这是显示图像的代码:

def displayImage():
global window
global STEAM_USER

response = urllib2.urlopen('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' + STEAM_API_KEY + '&steamids=' + STEAM_USER + '&format=xml')
htmlSource = response.read()
soup = BeautifulSoup(htmlSource)
avatar = soup.find('avatarfull').getText()
print avatar

image_bytes = urllib2.urlopen(avatar).read()
data_stream = io.BytesIO(image_bytes)
pil_image = Image.open(data_stream)
tk_image = ImageTk.PhotoImage(pil_image)
label = Label(window, image=tk_image)
label.pack(padx=5, pady=5)

这是其余的代码:

import urllib2
from Tkinter import *
from PIL import Image, ImageTk
from bs4 import BeautifulSoup
import io

STEAM_API_KEY = 'XXXX'

global window

window = Tk()
window.title('Steam Avatar Viewer')
window.geometry("215x215")


def newUser():
    global window
    global entry


    entry = Entry(window)
    button = Button(window, text='Search', width=10, command=getUser)

    entry.pack()
    button.pack()
def getUser():
    global STEAM_USER
    global entry

    steamUser = entry.get()
    steamConverterURL = 'http://www.steamidconverter.com/' + steamUser
    steamIDURL = urllib2.urlopen(steamConverterURL)
    steamIDSource = steamIDURL.read()
    a = BeautifulSoup(steamIDSource)
    for hit in a.findAll(attrs={'id':'steamID64'}):
        STEAM_USER = hit.contents[0]
    print STEAM_USER

    displayImage()

def displayImage():
    global window
    global STEAM_USER

    response =    urllib2.urlopen('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' +     STEAM_API_KEY + '&steamids=' + STEAM_USER + '&format=xml')
    htmlSource = response.read()
    soup = BeautifulSoup(htmlSource)
    avatar = soup.find('avatarfull').getText()
    print avatar

    image_bytes = urllib2.urlopen(avatar).read()
    data_stream = io.BytesIO(image_bytes)
    pil_image = Image.open(data_stream)
    tk_image = ImageTk.PhotoImage(pil_image)
    label = Label(window, image=tk_image)
    label.pack(padx=5, pady=5)

newUser()
window.mainloop()

我相信这是非常简单的事情,但我无法弄清楚是什么导致图像不显示。

4

2 回答 2

4

当您将一个PhotoImage或其他 Image 对象添加到 Tkinter 小部件时,您必须保留自己对图像对象的引用。如果不这样做,图像将不会始终显示。这基本上就是我想说的:

photo = PhotoImage(...)
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

你可以参考这个

于 2014-03-29T04:24:58.410 回答
0

如前所述,您必须确保保留对图像的引用,否则它将被 Python 的垃圾收集器删除。除了上面的方法,我第一次学会克服这个问题的方法是简单地将图像附加到一个列表中,例如:

photo_list=[]
photo = PhotoImage(...)
photo_list.append(photo)

我当时喜欢这种方法,因为代码在做什么很明显(即存储图片以防止它被删除)。

无论哪种方式,您都必须简单地确保您的照片被保留!祝你好运 :)

于 2014-03-30T01:34:42.277 回答