如何在 KivyMD (Python) 中结合导航抽屉和多个屏幕?
Posted
技术标签:
【中文标题】如何在 KivyMD (Python) 中结合导航抽屉和多个屏幕?【英文标题】:How to combine Navigation Drawer and multiple Screens in KivyMD (Python)? 【发布时间】:2021-05-20 19:25:40 【问题描述】:我是一名编码初学者,我想制作一个包含带有导航抽屉的工具栏的移动应用程序,该应用程序应将用户带到应用程序中的不同屏幕。我搜索了很多解决方案,但并没有真正找到,因为有时整个代码都在 .kv 文件中,因此很难处理变量并打印它们,例如在此代码中:
How to switch between screens within the NavigationDrawer using KivyMD
我尝试将它与只使用 Kivy 而不是 KivyMD 的代码结合起来,但我失败了,因为它不是真正的移动应用程序:
https://www.techwithtim.net/tutorials/kivy-tutorial/multiple-screens/
我希望有人可以帮助我。 谢谢!
【问题讨论】:
【参考方案1】:from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivymd.app import MDApp
KV = '''
<ContentNavigationDrawer>:
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"
Screen:
MDToolbar:
id: toolbar
pos_hint: "top": 1
elevation: 10
title: "MDNavigationDrawer"
left_action_items: [["menu", lambda x: nav_drawer.set_state("open")]]
MDNavigationLayout:
x: toolbar.height
ScreenManager:
id: screen_manager
Screen:
name: "scr 1"
MDLabel:
text: "Screen 1"
halign: "center"
Screen:
name: "scr 2"
MDLabel:
text: "Screen 2"
halign: "center"
MDNavigationDrawer:
id: nav_drawer
ContentNavigationDrawer:
screen_manager: screen_manager
nav_drawer: nav_drawer
'''
class ContentNavigationDrawer(BoxLayout):
screen_manager = ObjectProperty()
nav_drawer = ObjectProperty()
class TestNavigationDrawer(MDApp):
def build(self):
return Builder.load_string(KV)
TestNavigationDrawer().run()
https://kivymd.readthedocs.io/en/latest/components/navigation-drawer/#switching-screens-in-the-screenmanager-and-using-the-common-mdtoolbar
【讨论】:
以上是关于如何在 KivyMD (Python) 中结合导航抽屉和多个屏幕?的主要内容,如果未能解决你的问题,请参考以下文章
KivyMD - 如何使用 KivyMD BottomNavigationItems 和屏幕本身内的按钮在屏幕上导航?