Search code examples
pythontkintercheckboxtk-toolkitcustomtkinter

How to add anonymous Checkboxes (or anything else) in ctkinter?


So recently I was creating an app that you can add Checkboxes to, and they were your works to do (to do list app), so I wanted to manage the Checkboxes that were added, and because they don't have names I couldn't manage them like saving their data or deleting them:

from customtkinter import *

app = CTk()


def add():
    CTkCheckBox(app, text=entry.get()).pack()


entry = CTkEntry(app, placeholder_text="Enter a name:") entry.pack()

add_button = CTkButton(app, text="Add", command=add) add_button.pack()


app.mainloop()

Something like this (And I had a simple question: how can I set the Checkboxes in checked mode?)


Solution

  • The simplest solution is to save the checkbuttons to a dictionary, with the key being the name.

    The following solution adds the checkbuttons to a global dictionary. When you press the "Get" button, the values will be printed out for each item in the dictionary.

    This code does not handle duplicates, but that's trivial to add at a later date.

    from customtkinter import *
    
    app = CTk()
    
    
    buttons = {}
    def add():
        name = entry.get()
        button = CTkCheckBox(app, text=name)
        button.pack()
        buttons[name] = button
    
    def get_values():
        for key in sorted(buttons.keys()):
            print(f"{key} = {buttons[key].get()}")
            
    entry = CTkEntry(app, placeholder_text="Enter a name:")
    add_button = CTkButton(app, text="Add", command=add)
    get_button = CTkButton(app, text="Get", command=get_values)
    
    entry.pack()
    add_button.pack()
    get_button.pack(side="bottom")
    
    app.mainloop()