0

I would like to generate checkbuttons for multiple items. Due to the repetition, I used a loop to initialize the widget and the default state, saving the BooleanVar() and widgets in separate lists. But by doing so, I can only check either check or uncheck all of them together.

I already tried to set different value to the BooleanVar in the list from within the loop, but to no avail.

ckbtnVarList = [tk.BooleanVar()]*len(ckbtnDict["Tag"])
ckbtnWdtList = [None]*len(ckbtnDict["Tag"])

for idx in range(len(ckbtnDict["Tag"])):
    ckbtnVarList[idx].set(1)
    ckbtnWdtList[idx]=ttk.Checkbutton(mainfrm, text=ckbtnDict["Text"][idx], variable=ckbtnVarList[idx]).pack()
2
  • Your code does not run. Please provide a Minimal, Complete, and Verifiable example. Be sure to include any imports and test data needed for it to run. Commented Sep 30, 2019 at 7:11
  • 1
    All the items in ckbtnVarList point to the same tk.BooleanVar. The list needs to be filled in a loop or list compréhension not with the multiply operator. Commented Sep 30, 2019 at 10:26

1 Answer 1

1

As specified in the comments above, you need to create your list of BooleanVar's with a list comprehension or a list. The below code shows how to do this. Since you didn't provide a complete code example, I've had to make some assumptions about your input data.

import tkinter as tk

ckbtnDict = {}
ckbtnDict['Tag'] = ["Tag1","Tag2","Tag3"]
ckbtnDict["Text"] = ["Txt1","Txt2","Txt3"]

mainfrm = tk.Tk()
ckbtnVarList = [tk.BooleanVar() for i in range(len(ckbtnDict["Tag"]))]
ckbtnWdtList = [None for i in range(len(ckbtnDict["Tag"]))]

for idx in range(len(ckbtnDict["Tag"])):
    ckbtnVarList[idx].set(1)
    ckbtnWdtList[idx]=tk.Checkbutton(mainfrm, text=ckbtnDict["Text"][idx], variable=ckbtnVarList[idx])
    ckbrnWdtList[idx].pack()

mainfrm.mainloop()
Sign up to request clarification or add additional context in comments.

2 Comments

Careful ckbtnWdtList is a list of Nones. As pack() returns None, it's Nones in the list not Checkbutton objects.
@TlsChris Well spotted. Edited my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.