Cactus Cactus - 2 months ago 7
Python Question

How can we use a loop to create checkbuttons from an array and print the values of the selected checkbutton(s)?

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.

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.

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.

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()


Solved

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()


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

Answer

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

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()

I hope this will be helpful.