How can you find which checkbutton is selected using Tkinter and a function? How can you find which checkbutton is selected using Tkinter and a function? tkinter tkinter

How can you find which checkbutton is selected using Tkinter and a function?


so here is an example of how You may want to do that:

from tkinter import Tk, Checkbutton, IntVarroot = Tk()selected = []class Choice:    def __init__(self, text):        self.text = text        self.state = IntVar()        self.checkbutton = Checkbutton(root, text=self.text, command=self.check,                                       variable=self.state, onvalue=1, offvalue=0)        self.checkbutton.pack()    def check(self):        state = self.state.get()        if state == 1:            selected.append(self.text)        if state == 0:            selected.remove(self.text)        print(selected)c1 = Choice('Apple')c2 = Choice('Orange')c3 = Choice('Pear')root.mainloop()

and in this case You can add as many Checkboxes as You pretty much want and the only thing You gotta do in You code to hardcode is to just initiate Choice class like so var_name = Choice('checkbutton name') where var_name is any variable name You want, and checkbutton name is any name You want (just to clarify).


You don't need a lot of if-else statements to know which fruit the user likes.

I'll show you two other ways to achieve the same thing.

The first way would be to create a dictionary with fruit names as keys and control variables as values.Now iterate through the items checking if the value of the control variable is 1.If it's 1 then append to the fruit list.

First way(using dictionary):

import tkinter as tkparent = tk.Tk()parent.title("My favorite fruits")l= tk.Label(parent, background="yellow", text="empty", width="30")l.pack()w = tk.Label(parent , text ="Select your favorite fruits!", bg="pink", fg = "white")txt = "you love "def print_choice():    global fruit_lst    for fruit, checked in fruits_dict.items():        if checked.get() and fruit not in fruit_lst:            print(fruit)            fruit_lst.append(fruit)        if fruit in fruit_lst and not checked.get():            fruit_lst.remove(fruit)        l.config(text=txt+' ,'.join(fruit_lst))    checkvar1= tk.IntVar()checkvar2 = tk.IntVar()checkvar3 = tk.IntVar()fruits_dict = {"Apple": checkvar1, "Pomegranate": checkvar2, "Banana": checkvar3}fruit_lst = []c1 = tk.Checkbutton(parent, text ="Apple", variable = checkvar1, onvalue=1, offvalue=0,height = 5, width =20, bg="pink", activebackground="yellow", activeforeground="orange", command=print_choice)c1.pack()c2 = tk.Checkbutton(parent, text ="Pomegranate", variable = checkvar2, onvalue=1, offvalue=0,height = 5, width =20, bg="pink", command=print_choice)c2.pack()c3 = tk.Checkbutton(parent, text ="Banana", variable = checkvar3, onvalue=1, offvalue=0,height = 5, width =20, bg="pink", command=print_choice)c3.pack()parent.mainloop()

You could avoid both the dictionary and the loop by using the below code:

import tkinter as tkparent = tk.Tk()parent.title("My favorite fruits")l= tk.Label(parent, background="yellow", text="empty", width="30")l.pack()w = tk.Label(parent , text ="Select your favorite fruits!", bg="pink", fg = "white")txt = "you love "def current(x, var):    global fruit_lst    if var.get():        fruit_lst.append(x['text'])    else:        try:            fruit_lst.remove(x['text'])        except ValueError:            pass            print(fruit_lst)checkvar1= tk.IntVar()checkvar2 = tk.IntVar()checkvar3 = tk.IntVar()fruit_lst = []c1 = tk.Checkbutton(parent, text ="Apple", variable = checkvar1, onvalue=1, offvalue=0)c1.config(command = lambda x=c1, var=checkvar1: current(x, var))c1.pack()c2 = tk.Checkbutton(parent, text ="Pomegranate", variable = checkvar2, onvalue=1, offvalue=0)c2.config(command = lambda x=c2, var=checkvar2: current(x, var))c2.pack()c3 = tk.Checkbutton(parent, text ="Banana", variable = checkvar3, onvalue=1, offvalue=0)c3.config(command = lambda x=c3, var=checkvar3: current(x, var))c3.pack()parent.mainloop()