【发布时间】:2021-04-16 11:09:58
【问题描述】:
我是使用 Tkinter 的 Python GUI 的新手,但遇到以下问题:
我正在尝试使用 Python 的 os 模块读取特定目录中的一些图像文件,并在单个窗口中将它们显示为 Tkinter 的标签。图像的平均大小为1990 x 1200。因此,我使用 Pillow 库调整了它们的大小,然后使用 for 循环将每个图像打包到窗口中。
但不是显示图像,而是显示一个空白窗口。我写了以下代码:
from PIL import Image, ImageTk
import tkinter as tk
import os
root = tk.Tk()
root.title("Photo Gallery")
root.geometry("655x350")
for (root_, dirs, files) in os.walk("Wallpaper"):
if files:
for file_ in files:
path = os.path.join("Wallpaper", file_)
image_ = Image.open(path)
n_image = image_.resize((100, 100))
photo = ImageTk.PhotoImage(n_image)
img_label = tk.Label(root, image=photo)
img_label.pack()
root.mainloop()
这是空白窗口的截图:
注意:我使用 Python 3.6.3 和 Pillow 8.2.0。
【问题讨论】:
-
你确定图片被选中了吗?
-
我认为有一个类似的帖子回答了这个问题,它提到了一次性变量或某事,但我不知道是否适用于你的情况(而且我不完全记得帖子是如何被称为“在函数 PhotoImage 中创建时图像未显示”的行)
标签: python tkinter python-imaging-library tkinter-label