Hippo
Hippo

Reputation: 13

Create multiple buttons and bind them to their corresponding label

I want to create multiple buttons and labels with a for loop. Each time Button1 is pushed the Label1 text should increment with 1 and the same thing goes for button2 > label2 and so on.

Each label should have its own NumericProperty.

My challenge is that I don't know how to "bind" a unique button instance with a unique label and class attribute instance. Please read the comments in the code example to understand my thoughts better.

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()

Upvotes: 0

Views: 188

Answers (1)

John Anderson
John Anderson

Reputation: 39092

You can use a dictionary to keep track of which Label is with each Button. Here is a modified version of your 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

Upvotes: 1

Related Questions