garlic
garlic

Reputation: 197

Reference widget using id in Kivy (kv language)

I have the following in KV language (simplified example): My issue is with the last line (on_release).

#:import Factory kivy.factory.Factory

<MyCustomWidgets>:
    
    ListView:
        id: my_listview
    
    
<MainScreen>:
    
    Button:
        text: "Choose File"
        on_release: Factory.FileChooserDialog().open()
    
    MyCustomWidgets:
            
    
<FileChooserDialog@ModalView>:
    
    FileChooserIconView:
        id: filechooser

    Button:
        text: "OK"
        on_release: app.root.add_to_listview("Sample Text", app.root.ids.my_listview)

In Python, I have:

class MainScreen(BoxLayout):
    def add_to_listview(self, thelistview):
        # For testing purposes.
        print(type(thelistview))

In KV, on the last line, I'm trying to run a python method which adds a string to a ListView that has an id of my_listview.

I get this error:

AttributeError: 'super' object has no attribute '__getattr__'

Upvotes: 3

Views: 6125

Answers (1)

ikolim
ikolim

Reputation: 16041

Use a Kivy ObjectProperty, my_listview = ObjectProperty(None) and hook it up (my_listview: my_listview) to the id: my_listview defined in the kv file. Please refer to the example and output for details.

Example

main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty


class MyCustomWidgets(BoxLayout):
    my_listview = ObjectProperty(None)


class MainScreen(BoxLayout):

    def add_to_listview(self, *args, thelistview):
        # For testing purpose
        print(self)
        print(args[0])
        print(thelistview)


class TestApp(App):
    title = "Reference widget using id in Kivy (kv language)"

    def build(self):
        return MainScreen()


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

test.kv

#:kivy 1.10.0
#:import Factory kivy.factory.Factory


<MyCustomWidgets>:
    my_listview: my_listview
    ListView:
        id: my_listview


<MainScreen>:
    orientation: "vertical"

    Button:
        text: "Choose File"
        on_release: Factory.FileChooserDialog().open()

    MyCustomWidgets:
        id: my_cw


<FileChooserDialog@ModalView>:

    id: filechooser

    Button:
        text: "OK"
        on_release:
            app.root.add_to_listview("Sample Text", thelistview=app.root.ids.my_cw.my_listview)

Output

enter image description here

Upvotes: 4

Related Questions