簡體   English   中英

如何在 Tkinter 中即時顯示圖像?

[英]How to display image in Tkinter on the fly?

我編寫了一段代碼來在 Tkinter 應用程序中顯示圖像。 但是,除非我在將其分配給 label 之前讀取所有圖像,否則圖像不會顯示。 這是我的代碼:


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()

這不起作用,但是如果我將img_lst.append(filepath)替換為img_lst.append(imageRead(filepath))並將image_displayed = Label(image=readImage(img_lst[0]))替換為image_displayed = Label(image=img_lst[0])然后它工作。

也就是說,當我嘗試直接讀取圖像而不在 memory 中預加載圖像時,該應用程序不起作用。 我哪里錯了?

由於沒有變量來存儲readImage()返回的圖像的引用在以下行中:

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

圖像將被垃圾收集。 使用變量來存儲引用,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM