如何使用Tkinter在GUI中导入和显示图像列表?

2024-07-06 22:09:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我正在尝试从一个名为“gta”的文件夹加载图像,然后在我的应用程序上显示这些游戏徽标。程序没有错误,但我认为这是一个逻辑错误。我是Python新手,我不知道我的displayImg函数中可能存在一些作用域逻辑问题


Tags: fromimageimportimgosrootglobfile
2条回答

不确定它是否能工作,但尝试使用您从中获取图像的gta文件夹的路径,而不是其名称-用路径替换名称

Note: When a PhotoImage object is garbage-collected by Python (e.g. 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.

For more.

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

相关问题 更多 >