Adding values in list if checkbox is checked Python

Viewed 4630

I'm making a small program, I have 2 check boxes (text1 and text2). I want to append values (text1 and text2) to a List, If check boxes are checked. I want to print list [text1,text2]

from tkinter import *

myApp = Tk()
myApp.title("GUI app")
myApp.geometry("300x500")

List = []
varList = []

var1 = IntVar()
Checkbutton1 = Checkbutton(myApp, text="Text1", variable=var1,
                           onvalue=1, offvalue=0)
Checkbutton1.grid(row=0, column=1, sticky=W)

var2 = IntVar()
Checkbutton2=Checkbutton(myApp, text="Text2", variable=var2,
                         onvalue=1, offvalue=0)
Checkbutton2.grid(row=1, column=1,sticky=W)

varList.append(var1)
varList.append(var2)

def addtolist():
    for item in varList:
        if item.get() == 1:
            List.append(item)
            print(List)

b1 = Button(myApp, text="Add", command=addtolist)
b1.grid(row=1, column=2)

mainloop()
2 Answers

Use onvalue="Text", offvalue="" and var1 = StringVar() and then item.get() will return "Text" or empty string.


from tkinter import *

# --- functions ---

def addtolist():
    global List

    List = []
    for item in varList:
        if item.get() != "":
            List.append(item.get())
    print(List)

# --- main ---

List = []
varList = []

myApp = Tk()
myApp.title("GUI app")
myApp.geometry("300x500")

var1 = StringVar()
cb1 = Checkbutton(myApp, text="Text1", variable=var1,
                           onvalue="Text1", offvalue="")
cb1.grid(row=0, column=1, sticky=W)

var2 = StringVar()
cb2 = Checkbutton(myApp, text="Text2", variable=var2,
                         onvalue="Text2", offvalue="")
cb2.grid(row=1, column=1,sticky=W)

varList.append(var1)
varList.append(var2)

b1 = Button(myApp, text="Add", command=addtolist)
b1.grid(row=1, column=2)

mainloop()

Modification of furas code to make it easier to create lists

from tkinter import *


def addtolist():
    global List

    List = []
    for item in varList:
        if item.get() != "":
            List.append(item.get())
    print(List)


List = []
varList = []
myApp = Tk()
myApp.title("GUI app")
myApp.geometry("300x500")


class Check:
    x = 0
    def __init__(self, lbl):
        self.var = StringVar()
        self.cb = Checkbutton(myApp, text=lbl, variable=self.var,
                              onvalue=lbl, offvalue="")
        self.cb.grid(row=Check.x, column=1, sticky=W)
        Check.x += 1
        varList.append(self.var)


Check("Paul Weller")
Check("Nancy Reagan")
Check("Richard Gere")

b1 = Button(myApp, text="Add", command=addtolist)
b1.grid(row=1, column=2)

enter image description here

Related