Inserting images into a Tkinter frame

Asked

Viewed 725 times

-1

I’m trying to add an image inside a Frame using the Tkinter through the code below:

class Gui():
"""
Implements a GUI for Interactive Dictionary app
"""
def __init__(self, parent):
    self.parent = parent
    self.parent.title('Interactive Dictionary')
    self.logo_frame = Frame(self.parent, bg='yellow')
    self._layout_frames()
    self.set_logo_frame()

def _layout_frames(self):
    self.logo_frame.pack()

def set_logo_frame(self):
    img = Image.open("static/app_image.jpg")
    img = ImageTk.PhotoImage(image=img)
    panel = Label(self.logo_frame, image=img)
    panel.grid(row=0, column=0)


if __name__ == '__main__':
    window = Tk()
    app = Gui(window)
    window.mainloop()

My window is blank. Figure below: inserir a descrição da imagem aqui

I’m not visualizing the error, I imagine it’s something very simple. The path image is correct. What may be wrong?

2 answers

1


The problem is related to the way Tkinter/Tk manipulates images. Tk keeps a reference for images, while Tkinter does not. When the python Garbage Collector clears the Tkinter object, Tk keeps a reference.

Source: Why do my Tkinter images not appear?

0

I was able to insert an image into a frame with the code below:

from PIL import Image, ImageTk

root = Tk()
frame = Frame(root)
frame.pack()

bottomframe = Frame(root)
bottomframe.pack()

img = ImageTk.PhotoImage(Image.open("backgrond.jpg"))
panel = Label(frame, image = img)
panel.pack()


brownbutton = Button(bottomframe, text="Brown", fg="brown")
brownbutton.pack()

bluebutton = Button(bottomframe, text="Blue", fg="blue")
bluebutton.pack()

blackbutton = Button(bottomframe, text="Black", fg="black")
blackbutton.pack()

root.mainloop()

Basically inserting an image in a Label and passing the Frame to which it will be inserted as the first parameter. In my case, the frame or the bottomframe.

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.