[英]How to import and display list of images in GUI using Tkinter?
from tkinter import *
from PIL import Image, ImageTk
import glob, os
root = Tk()
root.geometry("800x600")
# Function to display image
def displayImg(img):
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
newPhoto_label = Label(image=photo)
newPhoto_label.pack()
# gta_images = []
os.chdir("gta")
for file in glob.glob("*.jpg"):
# gta_images.append(str(file))
displayImg(file)
print(file)
# print(gta_images)
root.mainloop()
I am trying to load images from a folder called "gta" and then display those game logos on my app.我正在尝试从名为“gta”的文件夹中加载图像,然后在我的应用程序上显示这些游戏徽标。 Program has no error but I think its a logical error.
程序没有错误,但我认为这是一个逻辑错误。 I am new to Python I don't know maybe there is some scoping logic problem in my displayImg funcion.
我是 Python 的新手,我不知道我的 displayImg 函数中可能存在一些范围逻辑问题。
Note: When a PhotoImage object is garbage-collected by Python (eg when you return from a function which stored an image in a local variable), the image is cleared even if it's being displayed by a Tkinter widget.
Note: When a PhotoImage object is garbage-collected by Python (eg when you return from a function which stored an image in a local variable), the image is cleared even if it's being displayed by a Tkinter widget.
from tkinter import *
from PIL import Image, ImageTk
import glob, os
root = Tk()
root.geometry("800x600")
photos = []
def displayImg(img):
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
photos.append(photo)#keep references!
newPhoto_label = Label(image=photo)
newPhoto_label.pack()
for file in glob.glob("*.jpg"):
displayImg(file)
print(file)
root.mainloop()
Not sure if it will work but try using the path of the gta folder you are getting the images from, instead of its name simply - replace the name with the path.不确定它是否会起作用,但尝试使用您从中获取图像的 gta 文件夹的路径,而不是简单地使用它的名称 - 用路径替换名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.