-1

I am trying to insert an image to a tkinter Label.

The image does not show itself in the label object. Could not find a clear solution on the Internet. `

Here is the source code of the python file:

import tkinter as tk
from PIL import Image, ImageTk


class LoginPage(tk.Tk):
    def __init__(self, WindowName='Login', WindowWidth=960, WindowHeight=540, bgColor='#181A20'):
        super().__init__()
        self.title(WindowName)  # Setting the Window Name
        self.configure(background=bgColor)  # Setting the Window BG Color

        # Centering the Window According to Window Size#
        scr_width = self.winfo_screenwidth()
        scr_height = self.winfo_screenheight()
        x = (scr_width/2) - (WindowWidth/2)
        y = (scr_height/2)-(WindowHeight/2)
        self.geometry('%dx%d+%d+%d' % (WindowWidth, WindowHeight, x, y))

        # Setting the Window Icon
        # Resizing the image
        png = Image.open('./res/logo_no_text_yellow.png')
        png = png.resize((50, 50))

        # Placing the Window Icon
        photo = ImageTk.PhotoImage(png)
        self.wm_iconphoto(False, photo)

        # Main Logo Label
        self.label = tk.Label(self, background=bgColor)
        png1 = Image.open('./res/logo yellow.png')
        png1 = png1.resize((148, 148))
        photo1 = ImageTk.PhotoImage(png1)
        self.label.configure(image=photo1)
        self.label.place(x=285, y=24)


test = LoginPage()
test.mainloop()

Here is the screenshot of the window:

enter image description here

1 Answers1

0

You need to save a reference to the image or Tkinter will not be able to find it:

    # Main Logo Label
    self.label = tk.Label(self, background=bgColor)
    png1 = Image.open('Canon.jpg')
    png1 = png1.resize((148, 148))
    photo1 = ImageTk.PhotoImage(png1)
    self.label.configure(image=photo1)
    self.label.image = photo1  # Save reference to image
    self.label.place(x=285, y=24)

or you can store the image reference in the object:

    # Main Logo Label
    self.label = tk.Label(self, background=bgColor)
    png1 = Image.open('Canon.jpg')
    png1 = png1.resize((148, 148))
    self.photo1 = ImageTk.PhotoImage(png1)  # Storing as instance variable
    self.label.configure(image=self.photo1)
    self.label.place(x=285, y=24)
figbeam
  • 7,001
  • 2
  • 12
  • 18