Python 如何动态引用kivy小部件?

Python 如何动态引用kivy小部件?,python,kivy,Python,Kivy,试着用一个变量来引用多个小部件。例如: #.kv Button: id: button1 Button: id: button2 Button: id: button2 #.py for x in range(3): self.ids.button[x].text = "This is button " + x 使用self.ids是dict(+getattr stuff)这一事实可能是最简单的: 您可能还可以使用getattr执行此操作: for x i

试着用一个变量来引用多个小部件。例如:

#.kv
Button:
    id: button1

Button:
    id: button2

Button:
    id: button2

#.py
for x in range(3):
    self.ids.button[x].text = "This is button " + x

使用self.ids是dict(+getattr stuff)这一事实可能是最简单的:

您可能还可以使用getattr执行此操作:

for x in range(3):
    getattr(self.ids, 'button{}'.format(x)).text = 'This is button {}'.format(x)

这个语法中到底发生了什么-我猜Python用x的值替换{}。。。但为什么会这样,我以前没见过?为什么没有领导。在['按钮之前…?替换由.format()方法完成-您可以在文档中查找,这是python中进行字符串插值的标准方法[是访问特定值的另一种语法。您应该查看普通python文档和教程以了解这些内容。
for x in range(3):
    getattr(self.ids, 'button{}'.format(x)).text = 'This is button {}'.format(x)