Search code examples
pythonpython-3.ximagetkinterjpeg

Why Isn't My Image Showing With Tkinter?


Following this answer, I am trying to get an image to display, yet when I go and run it (nearly exactly as it is in the answer), the window doesn't display the image.

from PIL import Image
import tkinter

window = tkinter.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
imageFile = "/Users/glennsha/Desktop/APCS_Create/Rank_icons/champion1.jpg"
window.im1 = Image.open(imageFile)

input()
window.mainloop()

Why is it not displaying?


Solution

  • Just follow the answer in the same link you have quoted. I have added explanations to the relevant sections to help your understanding. You can read more about Image and ImageTk here.

    from PIL import Image, ImageTk # I have added the import of ImageTk 
    import tkinter
    
    window = tkinter.Tk()
    window.title("Join")
    window.geometry("300x300")
    window.configure(background='grey')
    imageFile = "/Users/glennsha/Desktop/APCS_Create/Rank_icons/champion1.jpg"
    
    #Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
    im1 = ImageTk.PhotoImage(Image.open(imageFile))
    
    #Next, you need to put your image into a widget before it can be visible.
    # Your reference answer used a Label widget. We will use the same here.
    # This Label widget is a child of "window" which is the Tk() window. 
    panel = tkinter.Label(window, image = im1)
    
    #Next you need to put the widget into the Tk() window before the widget can be made visible.
    # Here, the Pack geometry manager is used to put/locate the widget containing
    # the images into the Tk() Window.
    panel.pack(side = "bottom", fill = "both", expand = "yes")
    
    window.mainloop()