简体   繁体   中英

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

Here I am trying to create a list of three fruits, Apple,Pomegranate and Banana, and asking the user to select their favorite fruit. So I am defining a function print_choice that is called each time any checkbox is selected, and have defined an array fruits that appends the respective fruit to the array when the checkbox is selected. I have defined the array inside the function instead of global declaration since the values should not be added twice. However I am not able to get the choice to be printed inside a label box that supposed to display the list of fruits selected by the user. Could you please help me find out where I've made a mistake and how can I display the fruits selected?

 import tkinter as tk
from tkinter import *

parent = 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():
    fruits=list()
    global txt
    flag=0
    while flag==0:
         if checkvar1.get()==1 and checkvar2.get==0 and checkvar3.get()==0:
             fruits.append("Apple")
             flag=1
             break
         elif checkvar2.get()==1 and checkvar1.get()==0 and checkvar3.get()==0:
             fruits.append("Pomegranate")
             flag=1
             break
         elif checkvar3.get()==1 and checkvar1.get()==0 and checkvar2.get()==0:
             fruits.append("Banana")
             flag=1
             break
         elif checkvar3.get()==1 and checkvar1.get()==1 and checkvar2.get()==0:
             fruits.append("Banana")
             fruits.append("Apple")
             flag=1
             break
         elif checkvar3.get()==1 and checkvar1.get()==0 and checkvar2.get()==1:
             fruits.append("Banana")
             fruits.append("Pomegranate")
             flag=1
             break
         elif checkvar3.get()==0 and checkvar1.get()==1 and checkvar2.get()==1:
             fruits.append("Apple")
             fruits.append("Pomegranate")
             flag=1
             break
         elif checkvar3.get()==1 and checkvar1.get()==1 and checkvar2.get()==1:
             fruits.append("Banana")
             fruits.append("Apple")
             fruits.append("Pomegranate")
             flag=1
             break
         else :
             fruits.append(" ")

         for fruit in fruits:
             txt += fruit+" "
         l.config(text=txt)
    
   
    
    
    
    
    
checkvar1= tk.IntVar()
checkvar2 = tk.IntVar()
checkvar3 = tk.IntVar()


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

This is what I'm getting as the output:

在此处输入图像描述

Whenever I try to select a checkbox, Python stops responding. Is it possible that I'm running into an infinite loop somewhere?

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

from tkinter import Tk, Checkbutton, IntVar


root = 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 tk

parent = 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 tk

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM