user7907186
user7907186

Reputation:

Automatically switching checkboxes on tkinter

I would like to switch on the checkboxes (0, 2, 4) automatically with the click of a button. I have the following code. For some reason it dont work. Please help me.

from tkinter import *

class Error(Frame):

    def Widgets(self):
        for i in range(len(self.X)):
            self.X[i] = Checkbutton(self, text="%d"%(i,))
            self.X[i].grid(row=i, sticky=W)
            self.X[i].configure(variable = ("var_%d"%(i,)))
        self.button = Button(self, text = "set", command = self.test)
        self.button.grid(row=5, sticky=W)

    def test(self):
        for i in range(len(self.X)):
            if i == 0 or i == 2 or i == 4:
                set (("var_%d"%(i,))) == 1         


    def __init__(self,initial):      
        super(Error,self).__init__(initial)
        self.X = [{},{},{},{},{}]
        self.grid()
        self.Widgets()

Window = Tk()
Tool = Error(Window)
Window.mainloop()

Upvotes: 0

Views: 50

Answers (1)

figbeam
figbeam

Reputation: 7176

The way to handle checkboxes is to associate each box with a variable which reflects wether the box is checked or not.

For an array of checkboxes it is convenient to store these variables in a list. The way I would do it is to create an empty list and then append variables as I go along.

In the function test() I use enumerate in the for-loop as this is the recommended way to generate an index of the list.

from tkinter import *

class Error(Frame):
    def __init__(self, master):      
        super(Error,self).__init__(master)
        self.box_list = []  # List to holld checbox variables
        self.grid()
        self.Widgets()

    def Widgets(self):
        for i in range(5):
            var = BooleanVar()  # Create variable to associate with box
            cb = Checkbutton(self, text="%d"%(i,))
            cb.grid(row=i, sticky=W)
            cb.configure(variable=var)
            self.box_list.append(var)   # Append checkbox variable to list
        self.button = Button(self, text = "set", command = self.test)
        self.button.grid(row=5, sticky=W)

    def test(self):
        for i, var in enumerate(self.box_list):
            if i == 0 or i == 2 or i == 4:
                var.set(True)        

Window = Tk()
Tool = Error(Window)
Window.mainloop()

Upvotes: 1

Related Questions