无法在 tkinter window 中打开图像,任务是使用 os 模块制作图像库,但由于 Window 上没有显示任何内容,因此出现了一些错误

not able to open image in tkinter window, task was to make a gallery of images using os module but some error occurs as nothing is displayed on Window

问题是我的 window 没有在 Tkinter window 上显示我想要的任何图像 下面是我尝试过的代码,但出现了一些问题。图像文件夹与 python 文件位于同一文件夹中,并且在尝试打印 jpg 图像时出现了一些带有 fp 的东西。谁能解释一下那是什么

from Tkinter import *
import os
from PIL import Image, ImageTk

gallery_root = Tk()
gallery_root.geometry("738x638")

for (root, dirs, files) in os.walk("/img"):
   for file in files:
      if file.endwith(".png"):
          Label(image=PhotoImage(file=str(file))).pack()
      if file.endwith(".jpg"):
          Label(image=ImageTk.PhotoImage(Image.open()))
gallery_root.mainloop()

不要使用泛型 from tkinter import *,而是明确指定您使用的是什么。

对于图像显示,此代码应该有效:

image = ImageTk.PhotoImage(Image.open(filepath))
label = Label(image=image)
label.image = image
label.pack()

使用 filepath = os.path.join(root, file) 作为完整路径,而不是 file,后者只是文件名。

此外,你犯了很多错误......你试过你的代码吗? 例如,endwith 不存在。请改用 endswith。你的道路真的是"/img"吗?不应该是"./img"吗?