创建多个按钮并将它们绑定到相应的标签

Create multiple buttons and bind them to their corresponding label

我想用 for 循环创建多个按钮和标签。每次按下 Button1 时,Label1 文本应递增 1,对于 button2 > label2 等也是如此。

每个标签都应该有自己的 NumericProperty。

我的挑战是我不知道如何使用唯一标签和 class 属性实例“绑定”唯一按钮实例。请阅读代码示例中的注释以更好地理解我的想法。

class MainWidget(GridLayout):
    label_string1 = NumericProperty(0)
    label_string2 = NumericProperty(0)
    label_string3 = NumericProperty(0)

def __init__(self, **kwargs):
    super(MainWidget, self).__init__(**kwargs)
    self.cols = 2
    for i in range(1, 4):
        self.btn = Button(text=str(i))
        self.btn.ids = {self.btn: str(i)}
        self.add_widget(self.btn)
        self.lab = Label(text="0")
        self.lab.ids = {self.lab: str(i)}
        self.add_widget(self.lab)
        self.btn.bind(on_press=self.btn_clicked)

def btn_clicked(self, instance):
    val = list(instance.ids.values())[0]
    
    #The code below doesn't work but it's just included to hopefully explain better what I was thinking - Other solutions are very welcome too.
    
    #The button ID number should be used to identity the class attribute and the text of the button should be added to that attribute 
    self.label_string + val = label_string + val + int(instance.text)
    #The button ID number should be used to identity the lab and the attribute above should be the text of that label
    label.ids.val.text = self.label_string + val


class ButtonWidgetApp(App):
    pass

if __name__ == '__main__':
    ButtonWidgetApp().run()

您可以使用字典来跟踪每个 Button 对应的 Label。这是您的 MainWidget class:

的修改版本
class MainWidget(GridLayout):
    def __init__(self, **kwargs):
        super(MainWidget, self).__init__(**kwargs)
        self.cols = 2
        self.myIds = {}  # dictionary to keep track of Button to Label correspondence
        for i in range(1, 4):
            self.btn = Button(text=str(i))
            self.add_widget(self.btn)
            self.lab = Label(text="0")
            self.add_widget(self.lab)
            self.btn.bind(on_press=self.btn_clicked)
            self.myIds[self.btn] = self.lab  # keep track of which Label is with this Button

    def btn_clicked(self, instance):
        lab = self.myIds[instance]  # get the Label for this Button
        val = int(lab.text)  # convert Label text to an integer
        lab.text = str(val+1)  # increment val and update Label text