首页 > 解决方案 > Python(tkinter)获取检查了哪些检查按钮?

问题描述

我正在尝试构建一个 python 应用程序,我们可以在其中制定工作时间表。我希望能够为每位员工按下 2 个复选按钮,并将已签入的复选按钮导出到 CSV 文件中。我现在设置代码的方式是在 for 循环中生成检查按钮,所以我不能给它们单独的名称/值。有没有办法我可以看到哪些被按下?

(变量“times”包含所有可用时间的列表,从 14:00 开始,到 23:00 结束)

#building UI
master = Tk()
emplindex = 1
timeindex = 1
for i in times:
    timelabel = Label(master, text=" " + i + " ").grid(row=0, column=timeindex)
    timeindex +=1
for i in employees:
    namelabel = Label(master, text=i[1]).grid(row=emplindex, column=0)
    timeindex = 1
    for i in times:
        CB =  Checkbutton(master).grid(row=emplindex,column=timeindex)
        timeindex +=1
    emplindex +=1
buildbutton = ttk.Button(master, text = "BUILD SCHEDULE", command=lambda: buttonclicked()).grid(row=100)
def buttonclicked():
    selected = CB
master.mainloop()

这是 ui 输出的内容

标签: pythontkintercheckbox

解决方案


您需要将变量与检查按钮相关联,并将对按钮的引用保存在列表或字典中。然后,您可以遍历变量以确定检查了哪些变量。

这是一个简单的例子来说明这一点:

import tkinter as tk

def submit():
    for i, var in enumerate(cbvars):
        print(f"{i}: {var.get()}")

root = tk.Tk()

cbvars = []
for i in range(10):
    var = tk.IntVar(root, value=0)
    cbvars.append(var)
    cb = tk.Checkbutton(root, text=f"Item #{i}", variable=var)
    cb.pack(side="top", anchor="w")

button = tk.Button(root, text="Submit", command=submit)
button.pack()

root.mainloop()

推荐阅读