简体   繁体   English

如何使用 Tkinter 和 function 找到选择了哪个复选按钮?

[英]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.在这里,我试图创建一个包含苹果、石榴和香蕉这三种水果的列表,并要求用户 select 是他们最喜欢的水果。 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.因此,我正在定义ZC1C425268E68385D1AB5074C17A94F14F14Z PRINT_CHOICE,每次选择任何复选框时都称为,并定义了在选择复选框时将相应水果附加到数组的数组果实。 I have defined the array inside the function instead of global declaration since the values should not be added twice.我在 function 中定义了数组,而不是全局声明,因为不应将值添加两次。 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.但是,我无法选择在 label 框中打印,该框应该显示用户选择的水果列表。 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:这就是我作为 output 得到的:

在此处输入图像描述

Whenever I try to select a checkbox, Python stops responding.每当我尝试 select 复选框时,Python 停止响应。 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).在这种情况下,您可以根据需要添加任意数量的复选框,并且您在硬编码代码中唯一要做的就是像这样启动 Choice class var_name = Choice('checkbutton name')其中 var_name 是任何变量名您想要,并且检查按钮名称是您想要的任何名称(只是为了澄清)。

You don't need a lot of if-else statements to know which fruit the user likes.您不需要很多 if-else 语句就可以知道用户喜欢哪种水果。

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.现在遍历检查控制变量的值是否为 1 的项目。如果为 1,则 append 到水果列表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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