收集多个Tkinter检查按钮的输出

时间:2018-07-25 09:34:20

标签: python-3.x user-interface variables checkbox tkinter

我有一个字典,其中包含诸如devices = {'dev1': ['192.168.200.73', 'foo', 'bar'], 'dev2': ['192.168.200.109', 'foo', 'bar']}之类的数据,我将该字典打印为复选按钮,并且需要获取所选的复选按钮名称。基本代码:

for name in devices:
v1 = BooleanVar()
c= Checkbutton(top, text=name, variable= v1)
c.grid(columns=1, rows= rs)
rs +=1

谢谢。

1 个答案:

答案 0 :(得分:0)

from tkinter import *

root = Tk()

devices = {'dev1': ['192.168.2.73', 'foo', 'bar'],
           'dev2': ['192.168.2.109', 'foo', 'bar']}

check_dict = dict() # Dict of checkbox names and IntVars
for name in devices:
    var = IntVar()      # Create an IntVar for the checkbox
    chk = Checkbutton(root, text=name, variable=var, onvalue = 1, 
                      offvalue = 0, height=5, width = 20)
    chk.pack()
    check_dict[name] = var  # Save name and IntVar reference

def go(event):  # Prints out all checkbox IntVars on <space>
    for name, var in check_dict.items():
        print(name, var.get())

root.bind('<space>', go)
root.mainloop()

使用列表和网格的示例:

from tkinter import *

root = Tk()

devices = {'dev1': ['192.168.2.73', 'foo', 'bar'],
           'dev2': ['192.168.2.109', 'foo', 'bar']}

check_list = [] # List of chexkbox names and IntVars
for name in devices:
    var = IntVar()          # Create an IntVar for the checkbox
    chk = Checkbutton(root, text=name, variable=var, onvalue = 1, 
                      offvalue = 0, height=5, width = 20)
    chk.grid()
    check_list.append([name,var])  # Save name and IntVar reference

def go(event):  # Prints out all checkbox IntVars on <space>
    for v in check_list:
        print(v[0], v[1].get())

root.bind('<space>', go)
root.mainloop()