Bach Tran
Bach Tran

Reputation: 63

Stuck with Class Function in Kivy

So I 've been creating this Kivy App, but this happened

class MyScreenManager(ScreenManager):
    def __init__(self, **kwargs):
        super(MyScreenManager, self).__init__(**kwargs)
        '''conn = sqlite3.connect('first_db.db')
        c = conn.cursor()
        c.execute("SELECT name FROM sqlite_master WHERE type='table';")
        screens = c.fetchall()
        for i in range(len(screens)):
            self.add_note()
        c.close()'''
        self.add_note()
    def add_note(self, name = ""):
        self.add_widget(NoteScreen(name = name))
        print(self.parent)

my .kv file

    MDNavigationLayout:
        x: toolbar.height
        size_hint_y: 1.0 - toolbar.height/root.height

        MyScreenManager:
            id: screen_manager

            NoteScreen:
                name: "Home"

When I run the app, instead of printing out the parent of MyScreenManager which is MDNavigationLayout, it printed out "None". I don't know how to fix it. Can anybody help me?

Upvotes: 1

Views: 61

Answers (1)

Jason S
Jason S

Reputation: 13799

self.parent isn't available at the time of the __init__ method because the class is first instantiated, then added to its parent.

Per documentation:

The parent of a widget is set when the widget is added to another widget

The base Widget.__init_() doesn't set self.parent.

Since Kivy uses an observable property for parent the action can be added in on_parent

def on_parent(self, instance, value):
    super(MyScreenManager, self).on_parent(instance, value)
    self.add_note()

Upvotes: 1

Related Questions