Python:Tkinter不显示我的图像或UI

时间:2014-07-24 23:59:03

标签: python image tkinter

我正在尝试创建一个右上角有图片的用户界面。这是我的代码:

import tkinter as tk
import urllib.request
import base64 as b64

class my_ui(tk.Tk):
    def __init__(self, parent):
        tk.Tk.__init__(self,parent)
        self.parent=parent
        self.intialize()

    def intialize(self):
        self.grid()

        #Welcome
        label = tk.Label(self,text="Welcome to my UI", anchor='center',fg='white',bg='blue')
        label.grid(column=0,row=0,columnspan=2,rowspan=2,sticky='EW')

        #Buttons
        button = tk.Button(self,text="Button 1",command=self.OnButtonClick)
        button.grid(column=0,row=3,sticky='W')

    def OnButtonClick(self):
        print("You clicked the button!")

if __name__ == "__main__":
    app = my_ui(None)

    #Logo URL - just a smiley face
    URL = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQCItlNQe0QaiuhkADUwgVTpx-Isaym6RAP06PHkzBe2Yza3a4rYIkHuB8"
    u = urllib.request.urlopen(URL)
    raw_data = u.read()
    u.close()
    b64_data = b64.encodestring(raw_data)
    photo = tk.PhotoImage(data=b64_data)

    logo = tk.Label(app, image=photo)
    logo.image = photo                  # To save it in memory
    logo.pack()                         # If I exclude this line, UI works fine.
    app.title('My User Interface')
    app.mainloop()

我从网上提取.gif并返回带有我的功能的PhotoImage。当我运行它时,我没有错误 - 相反,我的tkinter窗口不会出现任何错误。当我拿出评论中提到的那条线时,我的用户界面很好(按钮,但没有图像)没有错误。

我不确定窗户的缺席究竟是什么意思。我在Mac OSx上运行Python 3.4.1。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

tk.PhotoImage对象被垃圾收集时,图像被“释放”,可以这么说。图像在技术上仍在使用,因此它不会被破坏,但它会被彻底消除。将您的return行替换为:

photo = tk.PhotoImage(data=b64_data)
return photo

请务必将photo声明为全局变量。