获取具有相同变量名称的多个CheckButton的值tkinter python

时间:2019-05-22 12:57:25

标签: python tkinter

我有一个函数,可以根据用户放入参数的文件来创建字典。

然后我创建一个GUI,该GUI创建的CheckButtons与字典中的元素一样多。

这是我的代码:

for element in self.listdiagram.dict_diagrams :
    self.diagramVar = IntVar()
    self.diagram = Checkbutton(self.window, text=element, variable=self.diagramVar, onvalue=1, offvalue=0)
    self.diagram.pack(side = BOTTOM)
self.validate = Button(self.window, text="Validate", command=self.validateCallBack, width=15, height=3)
self.validate.pack(side = BOTTOM)

问题是我无法访问特定检查按钮的状态,因为它们具有相同的变量名。 而且我不知道该如何命名。

我尝试使用setattr(self, element, 0)exec来创建带有地西唐纳元素名称的变量名,但是它没有用,因为str(element)可能很长。

我该怎么做?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

对此的一个非常简单的解决方法是使用列表,然后将每个Checkbutton添加到列表中。

例如:

self.diagramVars = []

for element in self.listdiagram.dict_diagrams :
    diagramVar = IntVar()
    diagram = Checkbutton(self.window, text=element, variable=diagramVar, onvalue=1, offvalue=0)
    diagram.pack(side = BOTTOM)

    self.diagramVars.append(diagramVar)

self.validate = Button(self.window, text="Validate", command=self.validateCallBack, width=15, height=3)
self.validate.pack(side = BOTTOM)
  问:目前,我只想打印每个复选按钮的状态   当我按下验证按钮,但我的下一步是例如   具有self.diagramVars = [1、0、0],因此选中了第一个checkButton   所以我想运行另一个功能的名称(或文本)   我不知道我是否清楚吗?

我认为,此for循环使用element作为键来创建字典是一个合适的解决方案(如果element可以用作text=element选项,则应该可以用作键)

self.diagramVars = {}

for element in self.listdiagram.dict_diagrams :
    diagramVar = IntVar()
    diagram = Checkbutton(self.window, text=element, variable=diagramVar, onvalue=1, offvalue=0)
    diagram.pack(side = BOTTOM)

    self.diagramVars[element] = diagramVar

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

创建此词典时,要检索CheckButton的值,将使用行diagramVars[element].get(),这将访问CheckButton的“实时”状态