Search code examples
pythonimagetkintergrid

Tkinter With Images


With the following code, I can not display an image in a tkinter cell:

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

root = Tk()
root.geometry=("1000x1000")

def orig():
    orig_image = filedialog.askopenfilename(filetypes=[("Image file", "*.jpg"), ("All files", "*.")])
    my_img = ImageTk.PhotoImage(Image.open(orig_image))
    lbl = Label(image=my_img)
    lbl.grid(row=0, column=0)


orig()

root.mainloop()

But, by taking this out of the method, it works fine:

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

root = Tk()
root.geometry=("1000x1000")

orig_image = filedialog.askopenfilename(filetypes=[("Image file", "*.jpg"), ("All files", "*.")])
my_img = ImageTk.PhotoImage(Image.open(orig_image))
lbl = Label(image=my_img)
lbl.grid(row=0, column=0)

root.mainloop()

What am I missing ?

This is part of a larger project where I want to display an "original" OCR scan image and then with other methods, display a "corrected image" next to the original image (in another column) to show if that correction was an improvement or not.


Solution

  • there are some issues of your code

    • Unfortunately, the geometry method is being assigned incorrectly. It should be invoked instead of assigned.

    • To the first code block, you made a definition of a function orig() but let it remain unevaluated.

    • The PhotoImage object needs to be held on to as an attribute to prevent it from being lost to garbage collection.

    try this way:

    from tkinter import *
    from tkinter import filedialog
    from PIL import Image, ImageTk
    
    root = Tk()
    root.geometry("1000x1000")  # Corrected: called as a method
    
    def orig():
        global my_img  # Important: keep a reference to prevent garbage collection
        orig_image = filedialog.askopenfilename(filetypes=[("Image file", "*.jpg"), ("All files", "*.*")])
        img = Image.open(orig_image)
        my_img = ImageTk.PhotoImage(img)
        lbl = Label(root, image=my_img)
        lbl.grid(row=0, column=0)
    
    orig()  # Call the function to open file dialog and display image
    root.mainloop()