【问题标题】:python tkinter show images in a directorypython tkinter 在目录中显示图像
【发布时间】:2017-03-09 13:44:53
【问题描述】:

我有一个包含一些图像的文件夹。我想在单个窗口中使用 tkinter 显示所有图像。此外,每当我单击窗口中显示的任何图像时,我都需要显示图像的路径。我尝试使用 for 循环,但它会打印所有图像文件路径。这是我试过的代码,

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

def getFileName(image):
    print str(image)

gtk = Tk()
def showImages(folder):   
    for images in os.listdir(os.getcwd()):
        if images.endswith("png"):
            im = Image.open(images)
            tkimage = ImageTk.PhotoImage(im)
            imageButton = Button(gtk, image=tkimage, command=getFileName(images)
            imageButton.image=tkimage
            imageButton.pack()
gtk.mainloop()

谁能说我做错了什么?

【问题讨论】:

  • 请向我们展示进口商品。您的代码无法运行!
  • 我现在已经添加了导入。
  • 您使用的是什么版本的 Python?以下行“imageButton.image=tkimage”给了我 Python 2.7 中的语法错误。
  • 我正在运行 python 2.7,它没有显示任何错误。我得到的只是空的窗口。
  • 你是如何安装PIL的?

标签: python tkinter


【解决方案1】:
for images in os.listdir(os.getcwd()):
        if images.endswith("png"):
            im = Image.open(images)
            tkimage = ImageTk.PhotoImage(im)
            handler = lambda img = images: getFileName(img)  #here modify
            imageButton = Button(gtk, image=tkimage, command=handler)#here
            imageButton.image=tkimage
            imageButton.pack()

因为按钮按下回调是在没有参数的情况下运行的,如果我们 需要将额外的数据传递给处理程序,它必须包装在一个对象中 通过延迟 调用实际的处理程序。在这里,按下按钮即可运行该功能 由 lambda 生成,间接调用层保留 来自封闭范围的信息。净效果是真实的 处理程序。 -- > 第 435 页

【讨论】:

  • RuntimeError: Too early to create image
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 2016-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多