How can we use a loop to create checkbuttons from an array and print the values of the selected checkbutton(s)?
<p>I have an array of strings, and I want to be able to use a loop to quickly create a lot of checkbuttons for them, because the idea is that the user can later add/delete items in the array, so it should be adaptable. </p>

<p>I'm not even sure if this is possible with the method I'm trying to use. The problem with the code below is that it only checks the very last checkbutton/the very last item in the array, so it always returns PY_VAR3 or 'd' etc.</p>

<p>It would be amazing if someone could help me understand what to do, even if it's a complete rewrite of the code. I'm completely stumped.</p>

<pre><code>from Tkinter import *


Window = Tk()

class Test:
    def __init__(self):

        array = ['a', 'b', 'c', 'd']

        def doCheckbutton():
            for i in array:
                self.var = StringVar()
                c = Checkbutton(Window, text='blah', variable=self.var, command=printSelection)
                c.pack()


        def printSelection():
            print(self.var)

        doCheckbutton()

Test()

Window.mainloop()
</code></pre>

<p><strong>Solved</strong> </p>

<pre><code>from Tkinter import *


Window = Tk()

class Test:
    def __init__(self):

        self.array = ['a', 'b', 'c', 'd']
        self.vars = [] #Array for saved values

        self.doCheckbutton()

    def doCheckbutton(self):
        for i in range(len(self.array)):
            self.vars.append(StringVar()) #create new item in vars array
            c = Checkbutton(Window, text=self.array[i], variable=self.vars[-1], command=lambda i=i: self.printSelection(i), onvalue='on', offvalue='off')
            c.pack()


    def printSelection(self, i):
        print(self.array[i] + ': ' + self.vars[i].get())

Test()

Window.mainloop()
</code></pre>

<p>When a checkbutton is ticked/unticked, it prints out statements such as:
c: on
c: off</p>

<p>You can create for each <code>CheckBox</code> a <code>StringVar</code> and save them in a list then Use <code>get</code> method on <code>StringVar</code> to get its value (<code>lambda</code> is used to passe the index in array list):  </p>

<pre><code>from Tkinter import *


Window = Tk()

class Test:
    def __init__(self):

        self.array = ['a', 'b', 'c', 'd']
        self.vars = []

        self.doCheckbutton()

    def doCheckbutton(self):
        for i in range(len(self.array)):
            self.vars.append(StringVar())
            self.vars[-1].set(0)
            c = Checkbutton(Window, text=self.array[i], variable=self.vars[-1], command=lambda i=i: self.printSelection(i), onvalue=1, offvalue=0)
            c.pack()


    def printSelection(self, i):
        print(self.vars[i].get())

Test()

Window.mainloop()
</code></pre>

<p>I hope this will be helpful.</p>

python tkinter