Tkinter: Configuring multiple buttons with images

I have a function that takes the names of image files and creates a grid of them as buttons using the image attribute, which is where the issue arises, since I need the button object to create the image due to another function of mine fit_image() (which in this case fits the image inside the object completely, hence full=True). The result of running this without adding the images to these buttons is fine and all the buttons are clickable:

        self.image_buttons = {}
        count = 0

        # goes by column
        for y in range(height_divisor):
            # row
            for x in range(width_divisor):
                self.image_buttons[count] = tk.Button(self.preview_frame)
                self.image_buttons[count].place(
                    relx=0 + (1 / width_divisor * x),
                    rely=0 + (1 / height_divisor * y),
                    relwidth=1 / width_divisor,
                    relheight=1 / height_divisor,
                    anchor="nw",
                )

                # self.current_image = fit_image(
                #     Image.open(names_of_files[count]), self.image_buttons[count], full=True
                # )

                # self.image_buttons[count].configure(image=self.current_image)
                count += 1
                

        print(self.image_buttons)

Result of print statement:

{0: <tkinter.Button object .!toplevel2.!frame2.!button>, 1: <tkinter.Button object .!toplevel2.!frame2.!button2>, 2: <tkinter.Button object .!toplevel2.!frame2.!button3>, 3: <tkinter.Button object .!toplevel2.!frame2.!button4>}

However, once I uncomment this code, only the last button is clickable and does have the image on it, but all the others are blank and not clickable buttons. I have tried putting the commented (image configuration) lines in a separate for loop afterwards to go through and configure each button to no avail. Though I’ve previously had this work and even tried combing through my repo‘s commits (nothing before Aug 8th should be relevant) to see how it worked before, it must’ve been working then I most likely broke it before committing.

Answer

This was solved thanks to @jasonharper ‘s comment by changing these two lines and adding a new dictionary:

        self.image_buttons, self.images = {}, {}
        #for loops here

                self.images[count] = fit_image(
                    Image.open(names_of_files[count]), self.image_buttons[count], full=True
                )

                self.image_buttons[count].configure(image=self.images[count])