繁体   English   中英

为什么在Tkinter中不显示图像? (Python 2.x)

[英]Why isn't an image displaying in tkinter? (Python 2.x)

好吧,我很困惑。 因此,我最近开始使用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()

我相信这很简单,但是我无法弄清楚是什么导致图像无法显示。

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

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

你可以参考这个

就像已经说过的那样,您必须确保对图像周围保持引用,否则它将被Python的垃圾收集器删除。 除了上述方法外,我最初学会解决该问题的方法是将图像简单地追加到列表中,例如:

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

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

无论哪种方式,您都必须简单地确保您的图片保持在周围! 祝好运 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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