如何从 python 中的循环获取所有值
How to get all values from loop in python
我使用 for 循环从名称列表中创建了多个复选按钮。由于有 500 多个名字,我想使用 for 循环而不是一个一个地输入。我需要找出从这些复选按钮中选择了哪些名称。但是无论我做什么,我都无法一一获取checkbuttons的值。在我的一些尝试中,我得到了一个单一的数值,但我无法获得每个复选按钮的值。我不知道我哪里做错了。我可以从这个循环中获取每个值吗?还是必须一一写出来?
## a list as an example (There are more than 500 people on the original list.)
name_list = ['John Smith', 'Granny Smith', 'Michael Smith', 'Big Smith', 'Hello Smith']
for record in name_list:
nameVar = IntVar()
cb_name = Checkbutton(root, text=record, variable=nameVar, bg="white", anchor="w")
cb_name.pack(fill="both")
您可以通过创建包含所有记录名称及其相应状态的字典来实现此目的(0 表示未选中,1 表示选中):
from tkinter import *
root = Tk()
name_list = ['John Smith', 'Granny Smith', 'Michael Smith', 'Big Smith', 'Hello Smith']
check_dict = {} # This dictionary will contain all names and their state (0 or 1) as IntVar
def getSelected():
# Check the state of all check_dict elements and return the selected ones as a list
selected_names = []
for record in check_dict:
if check_dict[record].get():
selected_names.append(record)
return selected_names
# Create the checkbuttons and complet the check_dict
for record in name_list:
nameVar = IntVar()
cb_name = Checkbutton(root, text=record, variable=nameVar, bg="white", anchor="w")
cb_name.pack(fill="both")
check_dict[record] = nameVar
# A button to print the selected names
Button(root, text="Show", command=lambda: print(getSelected())).pack()
root.mainloop()
在我的代码示例中,您可以调用 getSelected()
函数来获取所选记录名称的列表。
我使用 for 循环从名称列表中创建了多个复选按钮。由于有 500 多个名字,我想使用 for 循环而不是一个一个地输入。我需要找出从这些复选按钮中选择了哪些名称。但是无论我做什么,我都无法一一获取checkbuttons的值。在我的一些尝试中,我得到了一个单一的数值,但我无法获得每个复选按钮的值。我不知道我哪里做错了。我可以从这个循环中获取每个值吗?还是必须一一写出来?
## a list as an example (There are more than 500 people on the original list.)
name_list = ['John Smith', 'Granny Smith', 'Michael Smith', 'Big Smith', 'Hello Smith']
for record in name_list:
nameVar = IntVar()
cb_name = Checkbutton(root, text=record, variable=nameVar, bg="white", anchor="w")
cb_name.pack(fill="both")
您可以通过创建包含所有记录名称及其相应状态的字典来实现此目的(0 表示未选中,1 表示选中):
from tkinter import *
root = Tk()
name_list = ['John Smith', 'Granny Smith', 'Michael Smith', 'Big Smith', 'Hello Smith']
check_dict = {} # This dictionary will contain all names and their state (0 or 1) as IntVar
def getSelected():
# Check the state of all check_dict elements and return the selected ones as a list
selected_names = []
for record in check_dict:
if check_dict[record].get():
selected_names.append(record)
return selected_names
# Create the checkbuttons and complet the check_dict
for record in name_list:
nameVar = IntVar()
cb_name = Checkbutton(root, text=record, variable=nameVar, bg="white", anchor="w")
cb_name.pack(fill="both")
check_dict[record] = nameVar
# A button to print the selected names
Button(root, text="Show", command=lambda: print(getSelected())).pack()
root.mainloop()
在我的代码示例中,您可以调用 getSelected()
函数来获取所选记录名称的列表。