[英]Checkbox validation: how do i ensure user can only tick one box only?
I am trying to create a multiple choice quiz in Tkinter. 我正在尝试在Tkinter中创建一个多项选择测验。
Each question has between 2-4 different answers all displayed as checkboxes, how do I ensure the user can only tick one check box and not all of them? 每个问题都有2-4个不同的答案,所有答案都显示为复选框,如何确保用户只能勾选一个复选框而不是全部复选框?
Thanks 谢谢
Don't use checkboxes; 不要使用复选框; use radoibuttons instead.
改用radoibuttons。 The behavior of checkboxes and radiobuttons is well established -- checkboxes allow you to select N of N choices, radiobuttons are designed to allow you to select exactly 1 of N. Don't violate this design pattern or your users will be confused.
复选框和单选按钮的行为已得到很好的确定-复选框允许您选择N个选项中的N个,单选按钮旨在允许您选择N个中的1个。不要违反此设计模式,否则您的用户会感到困惑。
To make radiobuttons work, create a single StringVar and associate it with two or more radiobuttons. 要使单选按钮起作用,请创建一个StringVar并将其与两个或多个单选按钮关联。 All of the radiobuttons that share the same variable will work as a set, allowing only one to be selected.
共享相同变量的所有单选按钮将作为一个集合起作用,仅允许选择一个。
Although it's not stated by OP, if you're making a multiple choice quiz it might also be desirable for certain questions to have specific check boxes be mutually exclusive. 尽管OP并未说明,但是如果您要进行多项选择测验,则可能还需要某些问题将特定的复选框相互排斥。 Or, require that the user choose at most M out of N check boxes and have this requirement specifically stated in the question so that the user understands the design pattern.
或者,要求用户在N个复选框中最多选择M个,并在问题中明确说明此要求,以便用户理解设计模式。 To do this you can take advantage of the callback option of Checkbuttons:
为此,您可以利用Checkbuttons的回调选项:
from Tkinter import *
master = Tk()
choices = [IntVar() for x in range(4)]
now = None
buttons = None
def cb():
global now, buttons
if None != now:
buttons[now].deselect()
vals = [choices[i].get() for i in range(4)]
try: now = vals.index(1)
except ValueError: now = None
print "variables are",str([choices[i].get() for i in range(4)])
buttons = [Checkbutton(master, text="Choice "+str(i), variable=choices[i], command=cb) for i in range(4)]
for b in buttons: b.pack()
mainloop()
This example answers OPs specific question, but can be expanded upon to make legitimate changes to the operation of check boxes in specific situations. 此示例回答了OP的特定问题,但是可以扩展为在特定情况下对复选框的操作进行合理的更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.