Search code examples
pythontkintercustomtkinter

How can i loop through buttons and place them automatically in a grid?


This is the code:

import customtkinter as ctk

class App(ctk.CTk):
    def __init__(self):
        super().__init__()

        self.title('Searchbar')
        self.geometry('500x500')
        self.resizable(False, False)

        self.items = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item10', 'item11', 'item12']


        self.frame = ctk.CTkFrame(self)
        self.frame.pack(pady=5, padx=5, fill='both', expand=True)

    def update(self, data):
        for item in data:
            button = ctk.CTkButton(self.frame, text=item, width=50, height=50)
            button.pack()

if __name__ == '__main__':
    app = App()
    app.update(app.items)
    app.mainloop()

this is what i get:

enter image description here

but this is what i want: (don't mind the edit..)

enter image description here

I haven't tried anything since i don't know the solution.


Solution

  • You can use the enumerate() function to get the index and the item from a list and then use the index to determine the row and column to be used to put the button:

    def update(self, data):
        for i, item in enumerate(data):
            # 8 columns per row
            row, col = divmod(i, 8)
            button = ctk.CTkButton(self.frame, text=item, width=50, height=50)
            button.grid(row=row, column=col, sticky="ew", padx=5, pady=5)
    

    enter image description here