【发布时间】:2021-04-09 21:10:43
【问题描述】:
我尝试创建多个复选框并获取它们是否被选中的信息。为此,我尝试使用 tkinter。复选框的数量是可变的。到目前为止,我找到了一种使用以下代码创建复选框的方法。这样,创建了 10 个复选框,人们可以在其中勾选任何一个
class Example(tk.Frame):
def __init__(self, root, *args, **kwargs):
tk.Frame.__init__(self, root, *args, **kwargs)
self.root = root
self.vsb = tk.Scrollbar(self, orient="vertical")
self.text = tk.Text(self, width=40, height=20,
yscrollcommand=self.vsb.set)
self.vsb.config(command=self.text.yview)
self.vsb.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
n=10
for i in range(n):
cb = tk.Checkbutton(self, text="Modul %s" % i)
self.text.window_create("end", window=cb)
self.text.insert("end", "\n")
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
但是,信息不会保存在任何变量中。如果我在 cb 中添加要转储的变量,代码将检查每个复选框。编辑后的代码部分如下(抱歉没能突出显示添加的部分):
class Example(tk.Frame):
def __init__(self, root, *args, **kwargs):
tk.Frame.__init__(self, root, *args, **kwargs)
self.root = root
self.vsb = tk.Scrollbar(self, orient="vertical")
self.text = tk.Text(self, width=40, height=20,
yscrollcommand=self.vsb.set)
self.vsb.config(command=self.text.yview)
self.vsb.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
n=10
var1 = IntVar()
val =[]
for i in range(n):
cb = tk.Checkbutton(self, text="Modul %s" % i, variable=var1)
self.text.window_create("end", window=cb)
self.text.insert("end", "\n") # to force one checkbox per line
val.append(var1.get())
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
您能帮我在代码中添加什么以便能够让用户获得选中的模块吗?例如,如果有人勾选模块 0、2 和 6,我将在“val”变量中得到一个带有 [1, 0, 1, 0, 0, 0, 1, 0, 0, 0] 的列表
期待您的反馈。
【问题讨论】: