如何使用Python从多个Tkinter检查按钮获取文本值

2024-09-27 23:21:37 发布

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

我正在尝试找出如何从用户单击“提交”按钮时选择的所有复选按钮中获取文本值。到目前为止,我能够获取已选择按钮的索引号,但无法获取文本值。例如,如果第一个,选中第二个和第五个按钮,它将打印1,2,5,但不会打印实际文本值。Iv引用了另一篇关于使用.cget()的帖子,但运气不佳。我的下一个想法是使用字典将数字和文本值存储在一起,但我计划的唯一问题是将列表扩大。我在下面贴了代码和图片来帮助解释。有什么建议吗

from tkinter import *

sick = []

def getChecked():
   for i in range(len(sick)):
    selected = ""
    if sick[i].get() >= 1:
       selected += str(i)
       print(selected)


 root = Tk()
 root.geometry('850x750')
 root.title("Registration Form")

for i in range(6):
    option = IntVar()
    option.set(0)
sick.append(option)


   # Conditions checkbutton
 label_6 = Label(root, text="Have you ever had ( Please check all that apply ) :", width=50, font= 
                 ("bold", 10))
 label_6.place(x=35, y=330)

Checkbutton(root, command=getChecked, text="Anemia", variable=sick[0]).place(x=130, y=350)

Checkbutton(root, command=getChecked, text="Asthma", variable=sick[1]).place(x=270, y=350)

Checkbutton(root, command=getChecked, text="Arthritis", variable=sick[2]).place(x=410, y=350)

Checkbutton(root, command=getChecked, text="Cancer", variable=sick[3]).place(x=560, y=350)

Checkbutton(root, command=getChecked, text="Gout", variable=sick[4]).place(x=130, y=380)

Checkbutton(root, command=getChecked, text="Diabetes", variable=sick[5]).place(x=270, y=380)

# submit button
Button(root, text='Submit', command=getChecked, width=20, bg='brown', fg='white').place(x=180, y=600)

root.mainloop()

Tags: textin文本forrangeplacerootvariable
1条回答
网友
1楼 · 发布于 2024-09-27 23:21:37

您需要在循环中移动sick.append(option)

for i in range(6):
    option = IntVar()
    option.set(0)
    sick.append(option)

此外,如果您使用所需的值作为checkbutton的值,则效率会更高

例如,从使用StringVar开始,并将值初始化为空字符串:

for i in range(6):
    option = StringVar(value="")
    sick.append(option)

接下来,将onvalue设置为checkbutton所需的值,将offvalue设置为空字符串:

Checkbutton(..., variable=sick[0], onvalue="Anemia", offvalue="")
Checkbutton(..., variable=sick[1], onvalue="Athma", offvalue="")
Checkbutton(..., variable=sick[2], onvalue="Arthritis", offvalue="")
Checkbutton(..., variable=sick[3], onvalue="Cancer", offvalue="")
Checkbutton(..., variable=sick[4], onvalue="Gout", offvalue="")
Checkbutton(..., variable=sick[5], onvalue="Diabetes", offvalue="")

现在,可以按如下方式打印值:

def getChecked():
    for var in sick:
        value = var.get()
        if value:
            print(value)

或者更简短的打印逗号分隔列表:

def getChecked():
    values = [var.get() for var in sick if var.get()]
    print("choices:", ", ".join(values))

这样做的好处是,值不必与标签相同。例如,如果这些值要发送到数据库,并且需要全部小写,则标签可以大写,但值可以小写

相关问题 更多 >

    热门问题