Vaibhav Sharma
Vaibhav Sharma

Reputation: 11

How to get the state of a Checkbutton in python?

I am working on my school project and I am stuck with one thing that is how to get the states of the checkbuttons. I used for loop to create the checkbuttons as there are many checkbuttons. I just don't know how to get the state of the checkbuttons.

Here 'entry1' refers to a list which is needed to input by the user and active_state will store the active state of the checkbuttons.

        active_state=[]
        for i in range (0,len(entry1)):
                    var=IntVar()    
                    check_btn=ttk.Checkbutton(update_record_window,text=entry1[i])
                    check_btn.grid(column=0,row=1+i)
                    active_state.append(var)
        print(active_state)

Please if anybody can tell me what I am doing wrong, it would be very grateful of you. Thanks in advance for the help.

Upvotes: 0

Views: 554

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386352

You need to associate the variable created in the loop with the checkbutton. Then it's just a matter of iterating over the variables and getting the values.

var=tk.IntVar()
check_btn=ttk.Checkbutton(..., variable=var)
...
print([var.get() for var in active_state])

Of course, you need to wait until the user has had a chance to interact with the checkbuttons before printing. Usually that means to put the print statement in a function that is called in response to an event.

Upvotes: 1

Related Questions