Tony Springs
Tony Springs

Reputation: 85

Get same photo in each grid button in python

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

Upvotes: 0

Views: 361

Answers (1)

Dan Vanatta
Dan Vanatta

Reputation: 41

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

Upvotes: 2

Related Questions