1

I am trying to add a bunch of images from a folder using a for loop using tkinter and I want each image to be placed on row = 20, but change columns for each image. So , I will want an image on (20,10), (20,11), (20,12) and so on. This works when I use grid for individual images, but I cant get it to work in a for loop where I want to add 5 images. Instead my first image starts appearing in the first row and first column but follows the column increments. Please let me know what I am doing wrong here? Thanks!

game = tkinter.Tk()
game.geometry("500x500")
images = random.sample(deck, 5)
path = "C:/Users/jhbhb/Documents/"

MAX_ROWS = 4
current_row = 20
current_column = 10

for file in images:
    im = Image.open(f"{path}/{file}.png")
    photo = ImageTk.PhotoImage(im)

    label = tkinter.Label(image=photo)
    label.image = photo
    label.grid(row=current_row, column=current_column)
    current_column += 1

game.mainloop()
Yagiz Degirmenci
  • 16,595
  • 7
  • 65
  • 85
rkm19
  • 149
  • 1
  • 7
  • you need to store a reference to your image so it doesn't get garbage collected. the simplest way is to add it to an array thats defined just before the for loop. – James Kent May 20 '20 at 09:15
  • It is because there is no widget before row 20 and column 10. – acw1668 May 20 '20 at 09:17
  • @JamesKent OP has already kept a reference of the image: `label.image = photo`. – acw1668 May 20 '20 at 09:18
  • sorry, i missed that. – James Kent May 20 '20 at 09:20
  • Does this answer your question? [what-does-weight-do-in-tkinter](https://stackoverflow.com/questions/45847313) and [tkinter gui layout using frames and grid](https://stackoverflow.com/a/34277295/7414759) – stovfl May 20 '20 at 09:39
  • Thanks a lot for your responses! well, I assumed that I could provide a particular space for each image , but it adjusts with respect to other images in the grid. I am now trying this on a canvas where I can specify co-ordinates for the widgets, which seems to be much easier and gives a cleaner look. Unless there are any disadvantages to using Canvas for such purposes. These links are very helpful and I will definitely give it a read :) – rkm19 May 20 '20 at 09:53

0 Answers0