pythonkivyids

Kivy: How to get the id of an object from itself?


I use a lot ids in kivy. I would like to get the id of my object from itself but I don't know how to write it correctly. (self.id doesn't work, it return None)

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

KV = '''
BoxLayout:
    ObjBoxLayout:
        id: my_box
'''

class MyApp(App):
   def build(self):
       box = Builder.load_string(KV)
       print(box.ids.keys())
       return box


class ObjBoxLayout(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        print(self.id)

if __name__ == "__main__":
   MyApp().run()

Solution

  • There is no direct way to do this, although technically you could iterate through the root's ids to find the one that matches.

    If you want this kind of functionality, it's probably a good idea to add your own identifying property that you set and access.