[英]How to display image in Tkinter on the fly?
I've written a snippet of code to display images in a Tkinter app.我编写了一段代码来在 Tkinter 应用程序中显示图像。 However, the image does not display unless I read all of the images before assigning it to the label.但是,除非我在将其分配给 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.这不起作用,但是如果我将img_lst.append(filepath)
替换为img_lst.append(imageRead(filepath))
并将image_displayed = Label(image=readImage(img_lst[0]))
替换为image_displayed = Label(image=img_lst[0])
然后它工作。
That is, the app does not work when I try to read the image directly without preloading it in memory.也就是说,当我尝试直接读取图像而不在 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:由于没有变量来存储readImage()
返回的图像的引用在以下行中:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.