首页 > 解决方案 > 执行多个变量函数(var_1,var_2,var_3)

问题描述

我还有一个小问题...

我想使用“setattr”创建多个变量

这工作得很好。它创建这些变量:

self.sectionButton_1 = Button(text=x)
self.sectionButton_2 = Button(text=x)
self.sectionButton_3 = Button(text=x)

现在我希望它们使用 tkinter 显示在窗口上,这样应该会发生这种情况:

self.sectionButton_1.grid(row=i, column=0)
self.sectionButton_2.grid(row=i, column=0)

等等..

但是,我如何在不编写上述十次的情况下,在循环中使用 tkinter 中的 .grid 创建 sectionButtons 的循环。

# Display Section selection
def checkSection(self):
    # Read all sections from config
    self.sections = config.sections()
    self.sectionsCount = str(len(self.sections))
    self.i = 0

    self.text = Label(text="Choose Section:" + self.sectionsCount)
    self.text.grid(row=1, column=0)
    for x in self.sections:
        i = +1
        setattr(self, 'sectionButton_' + str(i), Button(text=x))

我不太擅长解释,但希望它足以理解我的问题^^

如果没有,请评论,我会尽力回答

标签: pythonfor-looptkinter

解决方案


如果您有一组相同类型的相关变量,并且您对每个变量执行相同的操作,那么这是切换到使用列表而不是单个变量的自然位置。

您的代码将变得更像:

self.sectionButtons = []

for i, x in enumerate(self.sections):
    button = Button(text=x)
    button.grid(row=i+1, column=0)
    self.sectionButtons.append(button)

这还具有不再需要将变量名称构造为字符串和 use 的优点setattr,这通常表明有更好的方法。


推荐阅读