Tkinter:使用for循环Python创建检查按钮

时间:2019-01-01 21:29:08

标签: python user-interface tkinter

因此,我尝试使用for循环在Tkinter中创建多个检查按钮,方法是使用要显示的文本及其变量遍历嵌套列表。

我要自动执行此操作的原因是,我将来可能希望更改选中按钮的数量,因此我认为将其合并到列表中会更容易(以后可以更改) ),而不是手动执行。这是我尝试过的:

from tkinter import *

class Application(Frame):

    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        checkbttn_info = \ # nested list
        [("General Purposes", self.general_purposes),
        ("Young People",self.young_people),
        ("Education And Learning", self.education_and_learning),
        ("Healthcare Sector",self.healthcare_sector),
        ("Arts Or Heritage", self.arts_or_heritage),
        ("Infrastructure Support", self.infrastructure_support)
        ("Regenerating Areas", self.regenerating_areas)
        ("Community Cohesion", self.community_cohesion)]

        row, col = 2, 0
        for variable in checkbttn_info:
            variable[1] = BooleanVar()
            Checkbutton(self,
                    variable = variable[1],
                    text = variable[0]).grid(row = row, column = col, sticky = W)
            if col == 2:
               col = 0
               row +=1
            else:
               col +=1

不幸的是,我得到了例外:

AttributeError: 'Application' object has no attribute 'general_purposes'

我想我理解为什么会这样,但是我不知道如何解决。 Application对象没有任何'general_purposes'属性,因为我没有使用BooleanVar()对象实例化它,但是,除了上面的方法,没有其他方法可以想到。我尝试在for循环中实例化它,但是显然不起作用...

是否有一种方法可以解决该异常,或者有一种更好的方法来整体解决该异常?预先感谢您的任何建议!

1 个答案:

答案 0 :(得分:1)

我能看到的最明显的解决方案是列出名称([“ General Purposes”,“ Young People”,...]),然后在for循环中使用该列表。然后,让循环创建变量,并将其添加到字典中,名称为键,变量为值。

from tkinter import *

class Application(Frame):

    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        name_list = ["General Purposes", "Young People",
                     "Education And Learning", "Healthcare Sector",
                     "Arts Or Heritage", "Infrastructure Support",
                     "Regenerating Areas", "Community Cohesion"]

        row, col = 2, 0
        widget_dict = {}
        for name in name_list:
            variable = BooleanVar()
            c = Checkbutton(self, variable=variable, text=name)
            c.grid(row = row, column = col, sticky = W)
            widget_dict[name] = variable
            if col == 2:
               col = 0
               row +=1
            else:
               col +=1

root = Tk()
app = Application(root)
root.mainloop()

如果您想使其尽可能简单,只需在将它们添加到create_widgets()列表中之前在checkbttn_info函数中声明它们即可。