- Before posting this question, I referred to the previously posted answer. If you were looking for a default check method, I dare to advise for you refer to the following link:Tkinter: is there way to check boxes by default?
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.
CodePudding user response:
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()