S.Gu
S.Gu

Reputation: 649

How to select multiple checkbox then store values in a list? python

from tkinter import *

root = Tk()    

users = ['Anne', 'Bea', 'Chris', 'Bob', 'Helen']
selected_users=[]

for x in range(len(users)):
    l = Checkbutton(root, text=users[x][0], variable=users[x])
    l.pack(anchor = 'w')

root.mainloop()

I have this sample code, I need to make multiple selections in that users list, after I hit OK, it stores checked value into another list named selected_users for later use.

For example, when I run this code, a checkbox window pops out, and I tick Anne,Bob, click OK. selected_users is now ['Anne','Bob']. And Window disappears

Upvotes: 0

Views: 3026

Answers (3)

Derek
Derek

Reputation: 2234

Here is slightly more concise way.

Defines IntVars in check list

A Button to collect results in selected_users.

This version can be reused.

from tkinter import *

root = Tk()    

users = [ 'Anne', 'Bea', 'Chris', 'Bob', 'Helen' ]
check = []

def select( ):
    global selected_users
    selected_users = []
    for x, n in enumerate( check ):
        selected_users.append( n.get() )
        print( f'{users[ x ]} = {n.get()}' )

for x, n in enumerate( users ):
    check.append( IntVar( root, value = 0 ) )
    l = Checkbutton( root, text = n, variable = check[ x ] )
    l.pack(anchor = 'w')

but = Button( root, text = 'Ok', command = select, width = 20 )
but.pack( fill = 'both')

root.mainloop()

Upvotes: 1

user15801675
user15801675

Reputation:

You can do this:

from tkinter import *
root = Tk()    
users = ['Anne', 'Bea', 'Chris', 'Bob', 'Helen']
selected_users=[]
for x in range(len(users)):
    l = Checkbutton(root, text=users[x][0], variable=users[x],command=lambda x=users[x]:selected_users.append(x))
    l.pack(anchor = 'w')
Button(root,text="Ok",command=lambda: [print(selected_users),root.destroy()]).pack()
root.mainloop()

This will add the value to the list and when you hit Ok the window will disappear.

Adding more functionality to the program:

from tkinter import *
root = Tk()    
users = ['Anne', 'Bea', 'Chris', 'Bob', 'Helen']
users_l=[str(i) for i in range(len(users))]
selected_users=[]
def add_remove(user,var):
    if var.get()==0:
        try:
            selected_users.remove(user)
        except KeyError:
            pass
    else:
        selected_users.append(user)
for x in range(len(users)):
    users_l[x]=IntVar(0)
    l = Checkbutton(root, text=users[x], variable=users_l[x],offvalue=0,onvalue=1,command=lambda x=users[x],y=users_l[x]:add_remove(x,y))
    l.pack(anchor = 'w')
Button(root,text="Ok",command=lambda: [print(selected_users),root.destroy()]).pack()
root.mainloop()

Upvotes: 2

imxitiz
imxitiz

Reputation: 3987

This should work for you:

from tkinter import *

users=['Anne', 'Bea', 'Chris', 'Bob', 'Helen']

class Checkbar(Frame):
   def __init__(self, parent=None, picks=[]):
      Frame.__init__(self, parent)
      self.vars = []
      for pick in picks:
         var = IntVar()
         chk = Checkbutton(self, text=pick[0], variable=var)
         chk.pack()
         self.vars.append(var)
   def check(self):
    lst=list(map((lambda var: var.get()), self.vars))
    nlst=[u for l,u in zip(lst,users) if l==1]
    return nlst

root = Tk()
lng = Checkbar(root, users)
lng.pack()

def allstates(): 
  print(lng.check())
  root.quit()

b=Button(root, text='Check', command=allstates)
b.pack()
root.mainloop()

What we are doing here is:
We have a list of users in users and we create a check box using class Checkbar and pack it in root. Now we have to get the checked names only so, we created the button. When we click on that button, it triggers allstates function where we are trying to call Checkbar.check() function which is returning list of checked button only. We are doing this by: we have list of variables of checkbutton variable named as self.vars, and using lambda function we are trying to get all the button states by doing <Checkbutton>.get() and we got list from this like [0,0,0,1,0] and But we don't want list like that, we want list of names which is checked. So, we try to check if anne is checked or not if checked then add or if not check then go to next for all users.

Upvotes: 2

Related Questions