It is necessary to create an array of buttons with an image, each button has its own, but the image is molded only on the last button. Wooded Google, I realized that I need to somehow pass the 'image' parameter in an explicit form, but I can not figure out how to do it.

from tkinter import * from PIL import Image, ImageTk import os PATH = os.getcwd() work_dir = os.listdir(PATH + '\\' + 'images') num_of_pics = len(work_dir) field = Tk() row = 0 column = 0 for i in range(num_of_pics): img_name = (PATH + '\\' + 'images\\' + str(i) + ".png") img_op = Image.open(img_name) img = ImageTk.PhotoImage(img_op) but = Button(width=15, height=15, image=img) if i % 10 == 0: row += 1 column = 0 but.grid(row=row, column=column) column += 1 field.mainloop() 

    1 answer 1

    In your case, all images except the last one are deleted by the garbage collector (see, for example, the "Note" at the end of this article: PhotoImage ). From the point of view of the garbage collector, overwriting the old value of the img variable means that the previous value (image) is no longer referenced, so you can safely remove it from memory. To delete did not happen, you can save links to images in the list, then the images will not be deleted by the garbage collector, as long as the list exists:

     images = [] for i in range(num_of_pics): ... img = ImageTk.PhotoImage(img_op) images.append(img) # <<< сохраняем изображение в список but = Button(width=15, height=15, image=img) ... 

    Without saving the image in the list:

    no list

    With preservation:

    magic