Tkinter: How to default-check the checkbuttons generated by for loops

I try to set the default value for each item as the boolean value of the list, but it is still unchecked.

I have the code piece below. It was created using forloop to generate multiple checkbuttons. In the program I’m trying to implement, there are more of these check buttons. but I’ve reduced them to five below.

from tkinter import *

class App():
    def __init__(self, root):
        keys = [True, True, False, False, False]
        self.root = root
        for n in range(0, 5):
            self.CheckVar = BooleanVar()
            self.checkbutton = Checkbutton(self.root, text = 'test_' + str(n), variable = self.CheckVar.set(keys[n])).pack()
           
root = Tk()
app = App(root)
root.mainloop()

Or I also tried this way.

        for n in range(0, 5):
            self.CheckVar = BooleanVar(value=keys[n])
            self.checkbutton = Checkbutton(self.root, text = 'test_' + str(n), variable = self.CheckVar).pack()

And then these checkbuttons enable the user to modify the boolean values of the list.

>Solution :

Using the select() method you can check the boxes.

Change your for loop from:

for n in range(0, 5):
    self.CheckVar = BooleanVar()
    self.checkbutton = Checkbutton(self.root, text = 'test_' + str(n), variable = self.CheckVar.set(keys[n])).pack()

To:

for n, k in enumerate(keys):
    self.CheckVar = BooleanVar()
    self.checkbutton = Checkbutton(self.root, text = 'test_' + str(n))
    if k:
        self.checkbutton.select()
    self.checkbutton.pack()

Leave a Reply