简体   繁体   中英

How to display image in Tkinter on the fly?

I've written a snippet of code to display images in a Tkinter app. However, the image does not display unless I read all of the images before assigning it to the label. Here is my code:


from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title("Image Viewer app")


def readImage(image_name):
    my_img = Image.open(image_name)
    my_img = my_img.resize((640, 360), Image.ANTIALIAS)
    my_img = ImageTk.PhotoImage(my_img)
    return my_img

frame_lst = list(range(0,120))
img_lst = []
path = "usr/data/images"

start = time.time()
for file in os.listdir(path):
    if file.endswith('.jpg'):
        filepath = os.path.join(path, file)
        img_lst.append(filepath) #print time taken
end = time.time()
print(f"Time taken to read images is {end-start} seconds")
    
image_displayed = Label(image=readImage(img_lst[0]))
image_displayed.grid(row=0,column=0,columnspan=3)

root.mainloop()

This does not work but if I replace img_lst.append(filepath) with img_lst.append(imageRead(filepath)) and image_displayed = Label(image=readImage(img_lst[0])) with image_displayed = Label(image=img_lst[0]) then it works.

That is, the app does not work when I try to read the image directly without preloading it in memory. Where am I going wrong?

Since there is no variable to store the reference of the image returned by readImage() in the following line:

image_displayed = Label(image=readImage(img_lst[0]))

the image will be garbage collected. Use a variable to store the reference, like below:

image = readImage(img_lst[0]) # save the reference of the image
image_displayed = Label(image=image)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM