I want to create a list of checkboxes in Python with TkInter and try to select all checkboxes with a button.
Help me find a solution to my problem, I've wasted a lot of time on it.
from tkinter import *
def on_click():
lst = [interests[i] for i, chk in enumerate(chks) if chk.get()]
print(",".join(lst))
interests = ['Music', 'Book', 'Movie', 'Photography', 'Game', 'Travel']
root = Tk()
root.option_add("*Font", "impact 30")
chks = [BooleanVar() for i in interests]
Label(root, text="Your interests", bg="gold").pack()
for i, s in enumerate(interests):
Checkbutton(root, text=s, variable=chks[i]).pack(anchor=W) # W = West
Button(root, text="submit", command=on_click).pack()
root.mainloop()
CodePudding user response:
I added a new button called "select all" with the following line.
Button(root, text="select all", command=select_all).pack()
Which I connected to the select_all
function here.
def select_all():
for c in chks: c.set(True)
This function sets all checkboxes to True
.
Which leads to ...
from tkinter import *
def on_click():
lst = [interests[i] for i, chk in enumerate(chks) if chk.get()]
print(",".join(lst))
def select_all():
for c in chks: c.set(True)
interests = ['Music', 'Book', 'Movie', 'Photography', 'Game', 'Travel']
root = Tk()
root.option_add("*Font", "impact 30")
chks = [BooleanVar() for i in interests]
Label(root, text="Your interests", bg="gold").pack()
for i, s in enumerate(interests):
Checkbutton(root, text=s, variable=chks[i]).pack(anchor=W) # W = West
Button(root, text="select all", command=select_all).pack()
Button(root, text="submit", command=on_click).pack()
root.mainloop()