只允许用户一次选择一个复选框?
有没有办法让用户在一组 Checkbutton
选项中,只能选择一个?我能想到一些简单粗暴的解决办法,但我想要一个更优雅的方案。
1 个回答
6
你可以把所有的复选按钮连接到一个变量上,只需要给它们设置不同的 onvalue 值。
import tkinter
root = tk.Tk() #Creating the root window
var = tk.IntVar() #Creating a variable which will track the selected checkbutton
cb = [] #Empty list which is going to hold all the checkbutton
for i in range(5):
cb.append(tk.Checkbutton(root, onvalue = i, variable = var))
#Creating and adding checkbutton to list
cb[i].pack() #packing the checkbutton
root.mainloop() #running the main loop
我在循环中创建了这些复选按钮,方便演示。即使你一个一个地创建它们,也可以用同一个变量名,只要给它们设置不同的 onvalue 值。