tkinter checkbutton值打印

2024-05-23 18:16:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建用于创建作物列表的复选按钮。我想打印用户选择的作物,但它总是打印相同的作物(和我没有选择的作物),有人知道是什么作物吗

def set_check(event):
    global b
    var_lst=[]



    for widget in radios:
        widget.destroy()
    if cb_elemnt.get(): # get the crops according to element selection
        if cb_elemnt.get() != "N":
            crop_values = 
pd.unique(df.loc[df["elemnt"].eq(cb_elemnt.get()),"crop"])
        else:
            crop_values = pd.unique (df_nir.loc[df_nir["elemnt"].eq 
(cb_elemnt.get ()), "crop"])


    for num, t in enumerate(crop_values, 1): # create and add the crops to check button with number start from
        chkValue =IntVar ()
        checkbox_variable = IntVar ()
    # I need seperate var for each crop
        b = Checkbutton (top, text=t, variable=checkbox_variable, font=("Segoe UI Light", 10))
        checkbox_variables.append (checkbox_variable)
        b.grid (row=num, column=2, sticky='W', padx=40)
        radios.append (b)

def regression():
#PLSR
if cb_elemnt.get () != "N":
    if var1.get():
        element_u= cb_elemnt.get () #The element that the user selected
        print(element_u)
        for checkbox in checkbox_variables:  
            if checkbox.get ()==1:
                print(b.cget("text"))

Tags: thein作物cropdfforgetif
1条回答
网友
1楼 · 发布于 2024-05-23 18:16:41

让我们看看你在做什么:

您运行一个循环,该循环不断地将b重新分配为不同的Checkbuttonb将始终是您创建的最后一个Checkbutton

for num, t in enumerate(crop_values, 1):
    b = Checkbutton (top, text=t, variable=checkbox_variable, font=("Segoe UI Light", 10))

稍后,您将b视为它可以神奇地成为您在任何给定时间所需的任何Checkbutton

for checkbox in checkbox_variables:  
    if checkbox.get ()==1:
        print(b.cget("text"))

解决方案:

创建一个list{}的list,它的索引直接关联到您的checkbox_variables{}

例如:

for row, text in enumerate(crop_values, 1): 
    checkbox_variables.append(IntVar())
    checkboxes.append(Checkbutton(top, text=text, variable=checkbox_variables[-1], font=("Segoe UI Light", 10)))
    checkboxes[-1].grid(row=row, column=2, sticky='W', padx=40)

#and ...

for checkbox, var in zip(checkboxes, checkbox_variables):
    if var.get():
        print(checkbox['text'])

编辑:
进一步阅读代码后,您已经将Checkbutton附加到了?radios?(lol),但在下一个循环中无法使用radios获取相应的Checkbutton。顺便说一句:ARadiobutton和ACheckbutton不是一回事Checkbutton是一个单独的booleanRadiobutton是一组boolean值,其中一个值必须是True,并且只有一个值可以是True。你应该更准确地考虑变量名。如果您也开始使用Radiobutton,会怎么样?你会把你需要的list称为什么

相关问题 更多 >