python tkinter不在标签中显示图像

时间:2014-09-11 16:55:34

标签: python tkinter

我是python的新手。我已经尝试过如何显示Texbox,图像和按钮的代码。但图像不显示 请纠正我的代码以显示图像!

我的代码:

import Tkinter
from Tkinter import *
class myproject(Tkinter.Tk):
            def __init__(self,parent):
                Tkinter.Tk.__init__(self)
                self.button2()
                self.text()
                self.image()
            def button2(self):
                button2 = Tkinter.Button(self, text = "hello")
                button2.grid(column=5,row=7)
            def text(self):
                text = Tkinter.Text(self, height=3, width=31) 
                text.grid(column=1,row=3)
                text.insert(END, "Wiilliam Skakespeare")

            def image(self):
                logo = PhotoImage(file="linux.gif")
                w1 = Tkinter.Label(self, image=logo)
                w1.grid(column=5,row=7)

app = myproject(None)
app.mainloop()

1 个答案:

答案 0 :(得分:1)

您需要将PhotoImage保存为类变量,以便引用可以保留在内存中。 image()的以下方法应该有效:

def image(self):
    self.logo = Tkinter.PhotoImage(file="linux.gif")
    w1 = Tkinter.Label(self, image=self.logo)
    w1.grid(column=5,row=7)

此页面提供了更深入的解释:Effbot PhotoImage。具体这一节:

  

注意:当Python对垃圾收集PhotoImage对象时(例如   当您从在本地存储图像的函数返回时   变量),即使正在显示图像,图像也会被清除   Tkinter小部件。

为避免这种情况,程序必须对图像对象保留额外的引用。

相关问题