Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values in list if checkbox is checked Python

Tags:

python

tkinter

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()

1 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()
like image 143
furas Avatar answered Nov 22 '25 18:11

furas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!