0

我是使用 kivymd 并尝试使用 KivyMD 在 NavigationDrawer 中的屏幕之间切换的初学者,我正在阅读一些文档并最终得到了这段代码,但它不适用于我:

from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivymd.theming import ThemableBehavior
from kivymd.uix.list import MDList
from kivymd.app import MDApp



Window.size = (300, 500)
navigation_helper = """
Screen:
    MDToolbar:
        id: toolbar
        pos_hint: {"top": 1}
        elevation: 10
        title: "MDNavigationDrawer"
        left_action_items: [["menu", lambda x: nav_drawer.set_state("open")]]
        
    NavigationLayout:
        x: toolbar.height

        ScreenManager:
            id: screen_manager

            Screen:
                name: "scr 1"

                MDLabel:
                    text: "Go to Hell"
                    halign: "center"

            Screen:
                name: "scr 2"

                MDLabel:
                    text: "Hell"
                    halign: "center"

        MDNavigationDrawer:
            id: nav_drawer

            ContentNavigationDrawer:
                screen_manager: screen_manager
                nav_drawer: nav_drawer
           
                ScrollView:
                    MDList:

                        OneLineListItem:
                            text: "Screen 1"
                            on_press:
                                root.nav_drawer.set_state("close")
                                root.screen_manager.current = "scr 1"
            
                        OneLineListItem:
                            text: "Screen 2"
                            on_press:
                                root.nav_drawer.set_state("close")
                                root.screen_manager.current = "scr 2"


"""



class DemoApp(MDApp):
    class ContentNavigationDrawer(BoxLayout):
        screen_manager = ObjectProperty()
        nav_drawer = ObjectProperty()

    class DrawerList(ThemableBehavior, MDList):
        pass

    def build(self):
        screen = Builder.load_string(navigation_helper)
        return screen

    def on_start(self):
        pass


DemoApp().run()

但它给了我这个错误“AttributeError:'Screen'对象没有属性'nav_drawer'”,我不确定我做错了什么。

4

1 回答 1

0

id当您在定义 的同一规则中使用 an 引用对象时id,您不需要在它前面加上root

                    OneLineListItem:
                        text: "Screen 1"
                        on_press:
                            nav_drawer.set_state("close")
                            screen_manager.current = "scr 1"

                    OneLineListItem:
                        text: "Screen 2"
                        on_press:
                            nav_drawer.set_state("close")
                            screen_manager.current = "scr 2"
于 2020-07-21T17:18:14.213 回答