Python tkinter. Selected checkbuttons to list

Question:

I faced an issue and google did not give me an answer, so I am here.
My program has a list and converts it into checkbottons. Now I want to get the selected items to work with them. Here is the code:

import tkinter
from tkinter import *

mylist = ['Alfa', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 
          'Hotel', 'India', 'Juliett', 'Kilo', 'Lima']

class CheckButton:
    def __init__(self, master, title):
        self.var = IntVar()
        self.var.set(0)
        self.title = title
        self.cb = Checkbutton(master, text=title, variable=self.var, onvalue=1, 
                              offvalue=0)
        self.cb.pack(side = TOP)

def select():
    chosen = []
    for i in checks:
        #if ??? <--- Here is my issue
        #   chosen.append(checks[i])
    
#Window 
window = Tk()
f1 = Frame(window)
checks = []
for i in mylist:
    checks.append(CheckButton(window, i))
button = Button(window, text="Select!", command=select)
button.pack(side="bottom")
window.mainloop()

I tried to use get(i), checks.state(i) and some other, but it did not work. So what should I do to get the list of the chosen options?

Asked By: TeaPot

||

Answers:

Note that instance of CheckButton is not a checkbutton widget, so you cannot use .get() on it.

For your case, you need to use i.var.get() to get the state of the corresponding checkbutton:

def select():
    chosen = []
    for i in checks:
        if i.var.get():
            chosen.append(i.title)
    print(chosen)
Answered By: acw1668