Search code examples
pythonimagetkinterfiledialog

How can I display an image file with tkinter?


I want to do a Tkinter-based python program which would allow me to open an image file and to display it in a Label widget. But when I run the program and I click the button to call the OpenFile() function, it does not display the image. How can I display the image in the Label widget ?

Thank you !

My program looks like this :

import tkinter
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image, ImageTk

window = Tk() # App main window
menu_bar = Menu(window) # App menu bar

def OpenFile():
  "Open an image"
  try:
    file = filedialog.askopenfilename(initialdir= "E:", filetypes= [("Image file", (".png"))])
    image = Image.open(file)

    img = ImageTk.PhotoImage(image)
    #img.resize(50, 50)

    display = tkinter.Label(window)
    display.image = img
    display.pack()
    return file

  except FileNotFoundError:
    messagebox.showerror("Unfound file", "The selected file was not found.")


file_menu = Menu(menu_bar, tearoff= 0)  # Add a "File" menu to menu_bar
file_menu.add_command(label= "Open file...", command= OpenFile)
file_menu.add_command(label= "Quit...", command= window.destroy)
menu_bar.add_cascade(label= "File", menu= file_menu)
window.config(menu= menu_bar)
window.mainloop()

Solution

  • You forget to assign the image option of tkinter.Label:

    display = tkinter.Label(window, image=img) # need to set the image option
    

    I would suggest to create the label once and update its image option inside the function instead:

    ...
    def OpenFile():
      "Open an image"
      try:
        file = filedialog.askopenfilename(initialdir= "", filetypes= [("Image file", (".png"))])
        if file:
            img = ImageTk.PhotoImage(file=file)
            #img.resize(50, 50)
    
            #display = tkinter.Label(window, image=img)
            display.config(image=img)
            display.image = img
            return file
    
      except FileNotFoundError:
        messagebox.showerror("Unfound file", "The selected file was not found.")
    
    display = tkinter.Label(window) # create label once
    display.pack()
    ...