listkivyattributeerrorids

Kivy AttributeError: 'NoneType' object has no attribute 'ids' but why?


here main.py

from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivymd.app import MDApp
from kivymd.uix.list import OneLineListItem, MDList

class MyLayout(BoxLayout):
    pass



class Example(MDApp):
    lst_matches = ObjectProperty(None)
    def on_start(self):
        # List of possible crossword candidates.
        for i in range(20):
            self.root.ids.lst_matches.add_widget(OneLineListItem(text=f"Single-line item {i}"))

    def build(self):
        self.theme_cls.theme_style = "Light"
        return Builder.load_file("main.kv")

Example().run()

and then the main.kv file

#:kivy 2.1.0

<MyLayout>:
    BoxLayout:
        lst_matches: lst_matches
        orientation: 'vertical'
        ScrollView:
            halign: 'center'
            size_hint_y: 0.5
            size_hint_x: 0.5
            MDList:
                id: lst_matches

i added ObjectProperty(None) to lst_matches and correct the .kv file with lst_matches: lst_matches and then..

File "C:\Users\david\PycharmProjects\test kivy da lista\main.py", line 17, in on_start self.root.ids.lst_matches.add_widget(OneLineListItem(text=f"Single-line item {i}")) AttributeError: 'NoneType' object has no attribute 'ids'

but i can't understand why..


Solution

  • The problem is that you are returning the output of Builder.load_file("main.kv") from your build() method. However, that kv file does not create any widgets, so your root widget is None. The fix is a simple change to your build() method:

    def build(self):
        self.theme_cls.theme_style = "Light"
        Builder.load_file("main.kv")
        return MyLayout()
    

    In a kv file, the <> construction creates a rule for how a specific widget is to be built, but it does not actually create a widget. The Builder.load_file() loads the rule from your kv file, and the return MyLayout() actually creates an instance of MyLayout in accordance with the kv file rule.