Skip to content
Advertisement

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

Advertisement

Answer

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()
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement