Home > database >  Image not being displayed in tkinter python
Image not being displayed in tkinter python

Time:12-28

I've been using tkinter for a while now and currently I am working on an app in which I need to display an image at the home screen. The problem is that though the code is fine, the image is not being displayed. This is the image: enter image description here

This the code I am using. Please tell the problem:

    from tkinter import *
    from PIL import Image, ImageTk
    
    root = Tk()
    root.geometry("1000x700")
    root.minsize(1000, 700)
    root.maxsize(1000, 700)
    
    bg_img = Label(image=ImageTk.PhotoImage(Image.open("image_processing20200410-19194-aihwb4.png")), compound=CENTER)
    bg_img.pack(expand=1, fill=BOTH)

I have tried using the grid geometry manager but it is not working. Please help

CodePudding user response:

When you add a PhotoImage to a Tkinter widget, you have to keep a separate reference to the image object. Otherwise, the image will not show up.

CodePudding user response:

You need to define image object separately and then load it into Label:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()
root.geometry("1000x700")
root.resizable(False, False)
image = ImageTk.PhotoImage(Image.open("image_processing20200410-19194-aihwb4.png"))
panel = Label(root, image=image)
panel.pack(expand=1, fill=BOTH)
root.mainloop()

Output:

enter image description here

  • Related