Tkinter 复选框属性的问题。 AttributeError:“IntVar”对象没有属性“select”

问题描述 投票:0回答:1

我想单击

selectall
复选框,并自动选择
cbs
列表中的所有复选框。

我收到此错误:

AttributeError: 'IntVar' object has no attribute 'select'

在 StackOverflow 上阅读,我发现了类似的问题,但使用的解决方案不起作用:

selectall.configure(state=NORMAL)

我做错了什么?如何解决问题?谢谢你

    self.selectall = tk.IntVar()
    self.Checkbutton1 = tk.IntVar()
    self.Checkbutton2 = tk.IntVar()
    self.Checkbutton3 = tk.IntVar()

    cbs = [
        self.Checkbutton1,
        self.Checkbutton2,
        self.Checkbutton3,
        ]

    def function_select_all():
        for cb in cbs:
            cb.select()

    selectall = tk.Checkbutton(self, text="Select All",
                                     variable=self.selectall,
                                     onvalue=1, offvalue=0, height=1,
                                     command= function_select_all())

#Example of Checkbox
   Checkbutton1 = tk.Checkbutton(self, text="Checkbutton1",
                  variable=self.Checkbutton1, onvalue=1, offvalue=0, height=1,   
                  command=lambda: clicked(self.Checkbutton1.get(), partial(myfunction, self)))
   Checkbutton1.place(x=-2, y=69)
python python-3.x tkinter checkbox
1个回答
0
投票

该错误告诉您问题的根源:您试图在变量而不是检查按钮上调用

select()
,并且变量没有
select
方法。

由于所有复选按钮对选定状态使用相同的值,因此您可以调用变量的

set
方法来设置值:

def function_select_all():
    for cb in cbs:
        cb.set(1)

如果您更喜欢使用

select
方法,那么您需要迭代检查按钮而不是变量。您需要对列表中的复选按钮进行硬编码,或对函数中的复选按钮进行硬编码。

def function_select_all():
    for cb in self._checkbuttons:
        cb.select()
...
self._checkbuttons = [Checkbutton1, Checkbutton2, Checkbutton3]

然而,这并不是唯一的问题。您还需要确保与“全选”按钮关联的

command
是一个命令。您犯了一个常见错误:调用命令并将结果传递给
command
属性。相反,您需要将其设置为实际命令。

在以下示例中,请注意该值是

function_select_all
而不是
function_select_all()

selectall = tk.Checkbutton(...,
                           command= function_select_all)
© www.soinside.com 2019 - 2024. All rights reserved.