python-3.xfor-loopgetreturn-valuetkinter.checkbutton

How to get all values from loop in python


I created multiple checkbuttons using a for loop from a list of names. Since there are more than 500 names, I wanted to use the for loop instead of typing them one by one. I need to find out which names are selected from these checkbuttons. But no matter what I did, I couldn't get the values of the checkbuttons one by one. In some of my attempts, I got a single numeric value, but I couldn't get a value for each checkbutton. I don't know where I am doing wrong. Can I get each value from inside this loop? Or do I have to write them all one by one?

## a list as an example (There are more than 500 people on the original list.)

name_list = ['John Smith', 'Granny Smith', 'Michael Smith', 'Big Smith', 'Hello Smith']

for record in name_list:
    nameVar = IntVar()
    cb_name = Checkbutton(root, text=record, variable=nameVar, bg="white", anchor="w")
    cb_name.pack(fill="both")

Solution

  • You can achieve this by creating a dictionary that contains all record names and their corresponding state (0 for unselected and 1 for selected):

    from tkinter import *
    
    root = Tk()
    
    name_list = ['John Smith', 'Granny Smith', 'Michael Smith', 'Big Smith', 'Hello Smith']
    check_dict = {} # This dictionary will contain all names and their state (0 or 1) as IntVar
    
    def getSelected():
      # Check the state of all check_dict elements and return the selected ones as a list
      selected_names = []
      for record in check_dict:
        if check_dict[record].get():
          selected_names.append(record)
      return selected_names
    
    # Create the checkbuttons and complet the check_dict
    for record in name_list:
      nameVar = IntVar()
      cb_name = Checkbutton(root, text=record, variable=nameVar, bg="white", anchor="w")
      cb_name.pack(fill="both")
      check_dict[record] = nameVar
    
    # A button to print the selected names
    Button(root, text="Show", command=lambda: print(getSelected())).pack()
    
    root.mainloop()
    

    In my code exemple you can call the getSelected() function to get a list of the selected record names.