-2

I am trying to display an image as a label in tkinter, but its not displaying. Its showing a blank space where the image should be. Can someone please tell if I am doing this wrong

from tkinter import *
from PIL import Image, ImageTk

class Window:
    def __init__(self) -> None:
        self.root = Tk()
        self.root.title("Bingo")

        self.create_start_page()
        self.root.mainloop()

    def create_start_page(self):
        self.start_page = Frame(
            master=self.root, background="green", 
        )

        logo_img = PhotoImage(file='data/logo.png')
        logo_label = Label(master=self.start_page, image=logo_img)

        start_btn = Button(
            master=self.start_page,
            text="Start",
        )

        logo_label.pack()
        start_btn.pack(anchor="center", expand=True)
        self.start_page.pack(fill=BOTH, expand=True, side=TOP)
    
a = Window()

Image I am trying to insert

Result I am getting

I tried changing some oft the diffrent parameters to the pack(), only the size of the blank space changes, nothing else happens.

1 Answers1

0

The reason why the image is not displayed in the tkinter label is because the PhotoImage object is being garbage collected by Python before it can be displayed. To fix this issue, you need to keep a reference to the PhotoImage object by assigning it to an instance variable or to an attribute of another object that has a longer lifespan.

In your code, you can fix this issue by modifying the following line:

logo_img = PhotoImage(file='data/logo.png')

TO this:

self.logo_img = ImageTk.PhotoImage(file='data/logo.png')

Then, you can use self.logo_img instead of logo_img in the Label constructor:

logo_label = Label(master=self.start_page, image=self.logo_img)
Manvi
  • 171
  • 11