Search code examples
pythonuser-interfacetkintercustomtkinter

Tkinter how to sort dynamically added buttons


I am trying to create a pop up window in customtkinter with dynamically added checkboxes (this creates 80 checkboxes).

def open_secondary_window(self):
    # Create secondary (or popup) window.
    secondary_window = customtkinter.CTkToplevel()
    secondary_window.geometry(f"{400}x{200}")        
    secondary_window.title("Object Selection")
    
    # Create a button to close (destroy) this window.
    for i in range(len(class_names)): 
        c = customtkinter.CTkCheckBox(secondary_window, text=class_names[i])
        c.pack()
            
    button_close = customtkinter.CTkButton(
    secondary_window,
    text="Close window",
    command=secondary_window.destroy)
    button_close.place(x=75, y=75)`

This is the result

What I was thinking of doing is to iterate trough the list of checkboxes and every 10 to go to a new column:

for i in range(len(class_names)): 
    c = customtkinter.CTkCheckBox(secondary_window, text=class_names[i])
    c.grid(row=i, column=0)

the hard part is that I don't know how to iterate after every 10 columns to start from row 0 and column +1

Would anyone know a better solution on how to handle this

enter image description here


Solution

  • You can use python's divmod function to convert an integer into a row and column.

    for i in range(80):
        column, row = divmod(i, 10)
        cb = ctk.CTkCheckBox(root, text=f"{i+1}")
        cb.grid(row=row, column=column, sticky="nsew")
    

    screenshot