Yogaraj
Yogaraj

Reputation: 320

python tkinter show images in a directory

I have a folder which has some images. I want to display all the images using tkinter in a single window. Also whenever I click any image displayed in the window, I need to display the path of the image. I tried using for loop but it prints all the image file path. Here is the code I tried,

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

Can anyone say what I'm doing wrong?

Upvotes: 0

Views: 4549

Answers (1)

hankym
hankym

Reputation: 149

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

Because button-press callbacks are run with no arguments, if we need to pass extra datato the handler, it must be wrapped in an object that remembers that extra data and passes it along, by deferring the call to the actual handler. Here, a button press runs the function generated by the lambda, an indirect call layer that retains information from the enclosing scope. The net effect is that the real handler. -- << Programming Python>> page 435

Upvotes: 2

Related Questions