hellomynameisA
hellomynameisA

Reputation: 634

Tkinter get checkbuttons checked

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.

Upvotes: 1

Views: 1023

Answers (2)

Tls Chris
Tls Chris

Reputation: 3824

This fills a list with the ticked ingredients or by clearing the comment lists ingredients with 0 or 1. result may need to be a global variable to be useful. It depends on the rest of your code.

import tkinter as tk

root = tk.Tk() 
INGREDIENTS = ['cheese', 'ham', 'pickle', 'mustard', 'lettuce'] 
txt = tk.Text(root, width=40, height=20) 
variables = [] 
for i in INGREDIENTS: 
    variables.append( tk.IntVar( value = 0 ) ) 
    cb = tk.Checkbutton( txt, text = i, variable = variables[-1] ) 
    txt.window_create( "end", window=cb ) 
    txt.insert( "end", "\n" ) 
txt.pack() 
 
def read_ticks(): 
    # result = [( ing, cb.get() ) for ing, cb in zip( INGREDIENTS, variables ) ] 
    result = [ ing for ing, cb in zip( INGREDIENTS, variables ) if cb.get()>0 ] 
    print( result ) 
  
but = tk.Button( root, text = 'Read', command = read_ticks) 
but.pack()  
  
root.mainloop()

Upvotes: 2

Sharim09
Sharim09

Reputation: 6214

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()

Upvotes: 2

Related Questions