这可以通过在选中最大数量的 CheckButtons 时禁用所有未选中的 CheckButtons 来完成。禁用 CheckButtons 提高了用户友好性,因为它为用户提供了无法检查更多按钮的视觉线索。如果我们没有禁用 CheckButtons,用户可能会感到困惑,为什么当他尝试单击 CheckButton 时没有任何反应。
为了实现这个功能,我们必须为每个 CheckButton 连接一个回调函数。回调函数计算检查了多少个按钮,并相应地禁用或启用其他按钮。
我们要做的第一件事就是重写__init__ 方法。 Checkbar 需要一个新参数,可以同时检查多少个 Checkbuttons。我们还必须将回调函数连接到每个 CheckButton。我使用functools.partial将checkbutton的变量绑定到回调函数。
def __init__(self, parent=None, picks=[], maxselect=1, side=tk.LEFT,
anchor=tk.W):
super().__init__(parent)
self.maxselect = maxselect
# store all variables and checkbuttons; the callback function
# needs access to them
self._vars = []
self._checkbuttons = []
for pick in picks:
var = tk.IntVar()
# bind the callback function to each checkbutton
chk = tk.Checkbutton(self, text=pick, variable=var,
command=partial(self._var_toggled, var))
chk.pack(side=side, anchor=anchor, expand=tk.YES)
self._vars.append(var)
self._checkbuttons.append(chk)
现在剩下的就是实现回调函数了。它只需要计算检查了多少个检查按钮,并相应地启用或禁用它们:
def _var_toggled(self, var):
# count how many checkbuttons are checked
num = sum(v.get() for v in self._vars)
if num == self.maxselect:
# if we're at maxselect, disable all unchecked checkbuttons
for var, chk in zip(self._vars, self._checkbuttons):
if not var.get():
chk['state'] = tk.DISABLED
else:
# otherwise, re-enable all checkbuttons
for chk in self._checkbuttons:
chk['state'] = tk.NORMAL
(var参数来自我们之前使用的functools.partial。)
完整代码:
from functools import partial
import tkinter as tk
class Checkbar(tk.Frame):
def __init__(self, parent=None, picks=[], maxselect=1, side=tk.LEFT,
anchor=tk.W):
super().__init__(parent)
self.maxselect = maxselect
# store all variables and checkbuttons; the callback function
# needs access to them
self._vars = []
self._checkbuttons = []
for pick in picks:
var = tk.IntVar()
# bind the callback function to each checkbutton
chk = tk.Checkbutton(self, text=pick, variable=var,
command=partial(self._var_toggled, var))
chk.pack(side=side, anchor=anchor, expand=tk.YES)
self._vars.append(var)
self._checkbuttons.append(chk)
def _var_toggled(self, var):
# count how many checkbuttons are checked
num = sum(v.get() for v in self._vars)
if num == self.maxselect:
# if we're at maxselect, disable all unchecked checkbuttons
for var, chk in zip(self._vars, self._checkbuttons):
if not var.get():
chk['state'] = tk.DISABLED
else:
# otherwise, re-enable all checkbuttons
for chk in self._checkbuttons:
chk['state'] = tk.NORMAL