python - 执行多个变量函数(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))
我不太擅长解释,但希望它足以理解我的问题^^
如果没有,请评论,我会尽力回答
解决方案
如果您有一组相同类型的相关变量,并且您对每个变量执行相同的操作,那么这是切换到使用列表而不是单个变量的自然位置。
您的代码将变得更像:
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
,这通常表明有更好的方法。
推荐阅读
- javascript - 如何在 OpenLayers 中更改轴方向
- python - 如何使用递归垂直打印列表?
- nginx - 在 goaccess 中修改格式
- java - 检查编辑文本是否为空
- python-3.x - 我需要帮助弄清楚如何将此 python 的最终结果输出到 csv
- java - 如何在 SpringBootTest 中启动 SpringBootApplication
- javascript - 显示提交按钮js
- javascript - MERN,Mongoose:我随机化了一个数组并将其保存到 Mongo,但我必须刷新页面
- node.js - 为 Response Express 指定 A 类型
- python-3.x - 获取用于在差分进化工作者中使用的可腌制函数 = -1