0

I am trying to load 12 pictures from my directory of images by making a grid. when I use this code, I get the same picture in each button. I need a different photo in each button. Kinda brand new to Python.... sorry!

    import Tkinter as tk
    import glob
    from PIL import Image, ImageTk
    root = tk.Tk()

    for pl in glob.glob("C:/Users/Tony/Pictures/*.jpg"):
        im = Image.open(pl)
        im.thumbnail((180, 140), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(im)  
        for r in range(3):
            for c in range(4):
                tk.Button(root, image=photo).grid(row=r,column=c)
    root.mainloop()

Thanks

  • I think that you are always redrawing the same image 12 times (3x4). That's because you are always creating a button with the same image 12 times for each image (within the two last for-loops), in practice you will draw 12 times the 12 images, each one at a time and in the end you get the "last" image repeated 12 times. – jlnabais Sep 14 '15 at 18:00
  • This doesn't apply to your existing code, but if you ever put this code in a function or method, watch out for the [PhotoImage premature garbage collection problem](http://stackoverflow.com/questions/27430648/python-tkinter-2-7-issue-with-image) – Kevin Sep 14 '15 at 18:03

1 Answers1

2

Your loops aren't quite right, you probably end up with the last image on the all them? Heres what you are doing:

For each image paste image in each grid point (repeat for next image)

I would just make an array of all the filenames:

pl = glob.glob("*.jpg")
i = 0
for r in range(3):
   for c in range(4):
       im = Image.open(pl[i])
       i += 1

This lets you loop over your grid and use each photo only once

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Strange thing about this. Using your code, when I try to make the buttons like this: tk.Button(root, text=pl[i]).grid(row=r,column=c), I get 12 buttons with the name of each file in each button, but when I change the line to: tk.Button(root, image=photo).grid(row=r,column=c), I get only one image in the 12th position button. – Tony Springs Sep 15 '15 at 13:09
  • 1
    Show your code. It sounds like the previous image is being garbage collected but there is no way to tell. Since you want all 12 images in memory, you can also load them into a list first, and then connect each one to a button when the buttons are created. –  Sep 15 '15 at 18:12
  • @CurlyJoe Your gc answer was the problem. I added the following:label= tk.Label(image=photo), label.image=photo to the image to the im=Image.Open(pl) def and it worked great. I didn't realize I was sending all 12 images to memory. It would be better to make a list like you said, but then how do you connect each one to a button when the button is created? – Tony Springs Sep 16 '15 at 10:44
  • @DanVanatta, I changed the loops like you said and the grid worked right, especially after avoiding the garbage collection problem. Thanks... – Tony Springs Sep 16 '15 at 10:47