我有什么方法可以在tkinter中有一个checkbutton,如果选中,还会检查所有其他的checkbutton吗?
示例:
Checkbutton(root, text="A").grid(row=0, column=0, sticky=W)
Checkbutton(root, text="B").grid(row=1, column=0, sticky=W)
Checkbutton(root, text="C").grid(row=2, column=0, sticky=W)
Checkbutton(root, text="ABC").grid(row=3, column=0, sticky=W)
因此,如果你要检查ABC按钮,那么所有其他按钮也会被检查。有什么方法可以实现我想要的吗?
Python:3.4
操作系统:Windows
答案 0 :(得分:2)
在创建A,B和C复选框时,将它们保存在列表中;然后,当单击ABC时,您可以遍历列表并全部检查它们:
A = Checkbutton(root, text="A")
B = Checkbutton(root, text="B")
C = Checkbutton(root, text="C")
cbs = [A, B, C]
A.grid(row=0, column=0, sticky=W)
B.grid(row=1, column=0, sticky=W)
C.grid(row=2, column=0, sticky=W)
def checkall():
for cb in cbs:
cb.select()
Checkbutton(root, text="ABC", command=checkall).grid(row=3, column=0, sticky=W)
答案 1 :(得分:0)
给出Checkbutton
:
check = Checkbutton(root, text="Checkbutton",...)
check.grid(row=0, column=0, ...)
使用:check.deselect()
或(重新)检查:check.select()
答案 2 :(得分:0)
有关更完整的示例,您可能希望参考以下代码。它演示了一种方法,可以让复选框部分地确定另一个的价值。由于单个和组复选框之间的逻辑略有不同,因此使用了两个不同的事件处理程序。
#! /usr/bin/env python3
from tkinter import *
from tkinter.ttk import *
class Application(Frame):
@classmethod
def main(cls):
# Create a test environment to show how the class works.
NoDefaultRoot()
root = Tk()
root.title('Demonstration')
root.resizable(False, False)
root.minsize(250, 100)
frame = cls(root)
frame.grid()
root.mainloop()
def __init__(self, master=None, **kw):
super().__init__(master, **kw)
# Create variables for the checkboxes.
self.bv_a = BooleanVar(self)
self.bv_b = BooleanVar(self)
self.bv_c = BooleanVar(self)
self.bv_abc = BooleanVar(self)
self.cb_variables = self.bv_a, self.bv_b, self.bv_c
# Create each of the desired checkboxes.
options = dict(
master=self, command=self.update_any, onvalue=True, offvalue=False
)
self.cb_a = Checkbutton(text='A', variable=self.bv_a, **options)
self.cb_b = Checkbutton(text='B', variable=self.bv_b, **options)
self.cb_c = Checkbutton(text='C', variable=self.bv_c, **options)
options.update(command=self.update_all)
self.cb_abc = Checkbutton(text='ABC', variable=self.bv_abc, **options)
# Make sure the checkboxes are displayed.
self.cb_a.grid()
self.cb_b.grid()
self.cb_c.grid()
self.cb_abc.grid()
def update_any(self):
# Only check "ABC" if all the other boxes are checked.
self.bv_abc.set(all(variable.get() for variable in self.cb_variables))
def update_all(self):
# Copy the status of "ABC" to all of the other boxes.
for variable in self.cb_variables:
variable.set(self.bv_abc.get())
if __name__ == '__main__':
Application.main()
答案 3 :(得分:0)
将它们全部绑定到同一个变量:
var = IntVar()
Checkbutton(root, text="A", variable=var).grid(row=0, column=0, sticky=W)
Checkbutton(root, text="B", variable=var).grid(row=1, column=0, sticky=W)
Checkbutton(root, text="C", variable=var).grid(row=2, column=0, sticky=W)
Checkbutton(root, text="ABC", variable=var).grid(row=3, column=0, sticky=W)