python - 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()
解决方案
您需要将变量与检查按钮相关联,并将对按钮的引用保存在列表或字典中。然后,您可以遍历变量以确定检查了哪些变量。
这是一个简单的例子来说明这一点:
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()
推荐阅读
- mysql - CakePHP 2.x 字段为空或为空
- protractor - 在使用 Javascript 的量角器中,我们可以使用 try/catch 块来编写测试验证吗?
- php - Magento2:更新到 2.3.2。更改了订单 ID,想改回来
- performance - AWS EC2 t2.micro 无限 | 詹金斯马文 | 很慢| 构建挂起
- css - 附件按钮在 OS mobile 中不起作用
- python - 在熊猫 groupby 之后结合 idx 和 agg 结果
- asp.net-mvc - ReactJs - 在 onclick 事件中访问状态
- android - 如何使用 MAPBOX android SDK 添加/删除标记
- c# - 在 C# 中访问派生类中的 Windows 窗体组件
- c# - 在发出 HTTP POST 请求时捕获 ElasticSearch 异常