Oct-14-2025, 05:49 PM
So I've been trying to learn to use the tkinter with python to display images, and everything worked fine, when I displayed image like this:
What am I doing wrong here?
from tkinter import * import tkinter as tk from PIL import Image, ImageTk window = Tk() frame = tk.Frame(window, relief=RAISED, borderwidth=5, bg="yellow") frame.grid() image_path = '41Nc7sKMDgL.jpg' original_image = Image.open(image_path) original_image.thumbnail((400, 400) ,resample=Image.LANCZOS) tk_image = ImageTk.PhotoImage(original_image) image = tk.Label(frame, image=tk_image) image.grid(column=0, row=0) window.mainloop()but then, when I try to refactor the code into a function for example, I doesn't work:
from tkinter import * import tkinter as tk from PIL import Image, ImageTk def thumbnail(frm: tk.Frame, pth: str, sz: tuple[int, int] = (600, 600)): original_image = Image.open(pth) original_image.thumbnail(sz, resample=Image.LANCZOS) tk_image = ImageTk.PhotoImage(original_image) image = tk.Label(frm, image=tk_image) image.grid(column=0, row=0) window = Tk() frame = tk.Frame(window, relief=RAISED, borderwidth=5, bg="yellow") frame.grid() thumbnail(frame, '41Nc7sKMDgL.jpg') window.mainloop()In the first case, I get a window displaying an image as it should, but then in the last example, the window only shows a gray area where the image should be.
What am I doing wrong here?
