坚持使用 Kivy 中的 Class 函数

Stuck with Class Function in Kivy

所以我一直在创建这个 Kivy 应用程序,但是这件事发生了

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)

我的 .kv 文件

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

        MyScreenManager:
            id: screen_manager

            NoteScreen:
                name: "Home"

当我 运行 应用程序时,它没有打印出 MyScreenManager 的父级 MDNavigationLayout,而是打印出“None”。我不知道如何解决它。有人可以帮助我吗?

self.parent__init__ 方法时不可用,因为 class 首先实例化,然后添加到其父级。

根据 documentation:

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

基础Widget.__init_()没有设置self.parent

由于 Kivy 使用可观察的 property 作为 parent 可以在 on_parent

中添加动作
def on_parent(self, instance, value):
    super(MyScreenManager, self).on_parent(instance, value)
    self.add_note()