0

I'm trying add/remove an item (text of checkbox) to/from a list whenever a checkbox is checked/unchecked in tkinter. My idea was to add a command to the checkbutton, like:

cb = Checkbutton(master,...,command=some_fun)

but I cannot think of a way to define the function. I was thinking the function should contain the widget attribute cget('text'), but the problem is I have many checkboxes made with the help of a loop. I guess the question is: how can I reference the checkbox whose state got changed and is therefore calling the function some_fun?

The way I generated the checkboxes is:

cb_identities = []
for i in range(cb_max_num):
    cb = Checkbutton(frame_data,bg="white")
    cb_identities.append(cb)

And then I'm dynamically changing them depending on some radiobuttons:

def fun_chck(): #shows or hides checkbuttons based on radiobutton input
    data = read_data(rb_var.get())
    for i in range(cb_max_num):
        cbname = (cb_identities[i]) 
        if len(data)-1 < i:
            cbname.grid_forget()
        else:
            cbname.config(text=data[i]) #I would place some_fun here, which gets text option of checked box
            cbname.grid(row=i,column=1,sticky=W)
Sjotroll
  • 129
  • 1
  • 1
  • 7

1 Answers1

0

Update! I managed with the following code for anyone interested:

cb_var_init = [0] * cb_max_num #create the initial list of inactive checkbuttons, all 0
input_params=[]  #list which needs to be populated/depopulated based on checkbutton state

def get_data(data): #populates a list with parameter from checked checkbuttons, 
    global cb_var_init
    cb_var_list = list(map(lambda var: var.get(),list(cb_var.values())))
    for i in range(len(data)):
        if cb_var_list[i] > cb_var_init[i]:
            input_params.append(data[i])
        elif cb_var_list[i] < cb_var_init[i]:
            input_params.remove(data[i])
    cb_var_init = cb_var_list 
    return(input_params) 

cb_var is a dictionary of IntVars, and data is a list of checkbuttons' names.

As for the command on each checkbutton, I used cbname.config(text=data[i],command=lambda: get_data(data)) as suggested in another topic for functions with arguments. Now each time I check a checkbutton, I immediately get a list of parameters which should show in the next Frame, which is dynamically updated.

Sjotroll
  • 129
  • 1
  • 1
  • 7