Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading