Home > OS >  Tkinter get checkbuttons checked
Tkinter get checkbuttons checked

Time:05-10

I am new to Tkinter trying to get the value of the checked checkbuttons. So far, I am able to use a loop on Checkbutton in order to get a list of available check buttons from a list. How can I use a button to detect which of the check buttons are checked?

This is my code so far (for this part):

INGREDIENTS = ['cheese', 'ham', 'pickle', 'mustard', 'lettuce']
text = Text(root, width=40, height=20)
for i in INGREDIENTS:
    cb = Checkbutton(text="%s" % i, padx=0, pady=0, bd=0)
    text.window_create("end", window=cb)
    text.insert("end", "\n")
    cb.pack()

I know I have to use a button connected to a function in order to get the checked values, but I cannot think of a way to create the function and connect it to the list of check boxes.

Can you help me please? I can't use OOP, my code would be ruined (it is already long and I cannot reformat it all)

Thank you in advice.

CodePudding user response:

Try this one. As you say you don't want to your code get long. I think this is the solution to your problem.

Only Adding Two Lines.


INGREDIENTS = ['cheese', 'ham', 'pickle', 'mustard', 'lettuce']
text = Text(root, width=40, height=20)
for i in INGREDIENTS:
    var = IntVar()
    cb = Checkbutton(text="%s" % i, padx=0, pady=0, bd=0, offvalue=0,onvalue=1,variable=var)
    text.window_create("end", window=cb)
    text.insert("end", "\n")
    cb.bind('<Button-1>',lambda e,var=var,i=i:print(f'{i} is selected') if var.get()==0 else print(f'{i} is unselected'))
    cb.pack()

  • Related