how to obtain references to Widgets of the .kv file from Python (App)

713 views
Skip to first unread message

mjkuwp94

unread,
May 16, 2017, 2:41:36 PM5/16/17
to Kivy users support
Hello,

I have found that a reference to a Button (for example) can be sent with an event such as on_release.  This reference can be used in the Python code to work with the button and change text.

What I am trying to figure out is how to find a reference to other Widgets on my layout without having to click on them.  I've read the documentation about the collection of .ids but when I tried this I got the error "AttributeError: 'KivyTest1App' object has no attribute 'ids'"

Furthermore following some documentation about using an ObjectProperty fails and returns None.

The reason I would need to do this is that the result of some function might require me to 'grey' other buttons or panels to indicate to the user those functions should not be and cannot be used.

kivytest1.kv
#kivytest1.kv
BoxLayout:
    txt_inpt: txt_inpt
    orientation: 'vertical'
    BoxLayout:
        id: boxlayout1
        Label:
            text: 'my label'
        Button:
            id: box1
            text: 'box one'
            on_release: app.test_passing_reference(box1, 1)
        Button:
            id: box2
            text: 'box two'
            on_release: app.test_passing_reference(box2, 2)
        Button:
            id: f_but
            text: 'f but'
            
        TextInput:
            id: txt_inpt
            text: f_but.state
            on_text: app.check_status(f_but)


main.py
# main.py
# python 3.4.4
# Kivy v1.10.0
from kivy.app import App
from kivy.app import ObjectProperty


class KivyTest1App(App):

txt_inpt = ObjectProperty(None)

def build(self):
self.title = 'My Kivy Test One'

# uncomment this - it fails:
# AttributeError: 'KivyTest1App' object has no attribute 'ids'
# for key, val in self.ids.items():
# print("key={0}, val={1}".format(key, val))

def test_passing_reference(self, button_reference, button_number):
print(type(self))
button_reference.text = "I have a reference to this button " + str(button_number)

def check_status(self, btn):
print('text input text is: {txt}'.format(txt=self.txt_inpt))
# text input text is: None


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




Jacek Blocki

unread,
May 18, 2017, 3:18:49 AM5/18/17
to Kivy users support
App class does not have ids property (dictionary) since id does not inherit form Widget. You can create root widget class in .py:

class MyBoxLayout(BoxLayout):

    def print_ids(self):

        for key, val in self.ids.items():
            print("key={0}, val={1}".format(key, val))

In .kv use your class as root widget
#BoxLayout
<MyBoxLayout>:

The method print_ids() should work now if you invoke it.
JB

Reply all
Reply to author
Forward
0 new messages