如何将用户限制为一个选中按钮选中tkinter python

2024-09-27 00:16:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个带有多个checkbutton的GUI(checkbutton的数量是随机的,这取决于用户之前输入参数的文件)。你知道吗

所以我想知道是否有可能限制用户一次选中一个checkbuttons。你知道吗

我知道我可以创建单选按钮,但事实是我有相同的变量和相同的单选按钮值,当我使用单选按钮时,我可以选中两个按钮,我不能取消选中它们。这是我的密码:

for element in self.listdiagram.dict_diagrams:
    diagramVar = IntVar()
    diagram = Radiobutton(self.window, text=element, variable=diagramVar, value=1)
    diagram.pack(side=BOTTOM, expand=1)

    self.diagramVars[self.listdiagram.dict_diagrams.get(element)] = diagramVar

self.validate = Button(self.window, text="Validate", command=self.validateCallBack, width=15, height=3)
self.validate.pack(side=BOTTOM, expand=1)

我有一个代码,它与复选按钮,但我不知道如何限制一个选中。你知道吗

谢谢你的帮助!你知道吗

编辑:这是它看起来像,值是确定的,但都被选中,我不能取消选中他们,虽然单选按钮是当我选中一个,另一个是取消选中。你知道吗

https://i.stack.imgur.com/yKJt8.png

图2:https://i.stack.imgur.com/iOnNV.png


Tags: text用户selfelementwindow按钮sidedict
1条回答
网友
1楼 · 发布于 2024-09-27 00:16:50

Q: I know i can create radiobuttons but the fact is i have same variable and same value for radiobuttons and when i use radiobuttons i can check both buttons and i can't uncheck them.

Radiobuttons的工作方式与Checkbuttons有些不同。使用单选按钮,您可以创建“组”,其中只能选择一个组。方法是让所有的Radiobuttons使用与它们的variable=字段相同的IntVar(),然后让每个Radiobutton具有不同的值。你知道吗

您可以使用enumerate for loop在循环中执行此操作,如下所示:

diagramVars = {}
diagramVar = IntVar()

for i, element in enumerate(self.listdiagram.dict_diagrams):
    diagram = Radiobutton(self.window, text=element, variable=diagramVar, value=i)
    diagram.pack(side=BOTTOM, expand=1)

    self.diagramVars[self.listdiagram.dict_diagrams.get(element)] = diagramVar

self.validate = Button(self.window, text="Validate", command=self.validateCallBack, width=15, height=3)
self.validate.pack(side=BOTTOM, expand=1)

为此,您不需要字典,因为IntVar的值将是选中的单选按钮。你知道吗

例如,如果选择Radiobutton#1,则diagramVar.get()将返回0,如果选择Radiobutton#2,则diagramVar.get()将返回1,依此类推。这是因为单选按钮组需要相同的IntVar()

相关问题 更多 >

    热门问题