0

I am new to python.I have tried a code on how to display Texbox,image and button.But the image not displays Please rectify my code to display the image!

My code:

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 Answer 1

1

You need to save the PhotoImage as a class variable so the reference can stay in memory. The following method for image() should work:

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

This page provides a more in-depth explanation: Effbot PhotoImage. Specifically this section:

Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

To avoid this, the program must keep an extra reference to the image object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.