How to get ID of the button pressed in kivy?

Here is the example code that I am working with.

  • I am creating a pre-set number of buttons, each with their own ID numbers, based on the for loop

  • All the buttons have the same function attached to them when they are pressed

  • My goal is to get the ID name of the button that was pressed

  • Currently, my code is printing out the specific object address(?) like 0xAABBCCEE

  • I want to know how to print out the code in ID format, like “Button 3”

class MainScreen(GridLayout):

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.cols = 1
        MainScreenLayout = GridLayout()
        MainScreenLayout.cols = 3
       
       #for loop creating buttons with varying IDs
        NumberToCreate = 4
        for x in range(int(NumberToCreate)):
            aButton = Button(text='button text ' + str(x), on_press=self.press_auth)
            MainScreenLayout.add_widget(aButton)
            self.ids['button' + str(x)] = aButton

        self.add_widget(MainScreenLayout)

    #function for when button is pressed
    def press_auth(self, instance):
        print(str(instance)) #ulimate goal is get ID name and x number, to use later in code
        
class MyApp(App):
    def build(self):
        return MainScreen()
    
if __name__== '__main__':
    MyApp().run()

Answer

IDs in kivy are usually used in conjunction with kv files to track objectes through inheritance. You probably shouldn’t use the instance variable ids as a setter like you do as it is normally set internally to kivy and used as a getter by the developer.

An easier way to do what you want is to just set an arbitrary variable on each Button instance and track the differences there. If you plan on using deep inheritance and that’s why you want to use ids then I would set the id on the instance before adding it to the MainScreen.

The first way could be done simply like this:

class MainScreen(GridLayout):

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.cols = 1
        MainScreenLayout = GridLayout()
        MainScreenLayout.cols = 3
       
       #for loop creating buttons with varying IDs
        NumberToCreate = 4
        for x in range(int(NumberToCreate)):
            aButton = Button(text='button text ' + str(x), on_press=self.press_auth)
            aButton.my_id = x  # or 'button' + str(x) or whatever you want to use to track buttons
            MainScreenLayout.add_widget(aButton)

        self.add_widget(MainScreenLayout)

    #function for when button is pressed
    def press_auth(self, instance):
        print(str(instance.my_id)) #ulimate goal is get ID name and x number, to use later in code
        
class MyApp(App):
    def build(self):
        return MainScreen()
    
if __name__== '__main__':
    MyApp().run()