如何在没有 KV 语言的情况下使用 MDNavigationRail + MDNavigationRailItem
Posted
技术标签:
【中文标题】如何在没有 KV 语言的情况下使用 MDNavigationRail + MDNavigationRailItem【英文标题】:How to use MDNavigationRail + MDNavigationRailItem without KV language 【发布时间】:2021-06-03 14:36:02 【问题描述】:如何在没有 KV 语言的情况下创建MDNavigationRail
?我试过这段代码,但我得到了很多错误。
class MyApp(MDApp):
def build(self):
boxlayout1 = MDBoxLayout(orientation = "vertical")
toolbar = MDToolbar(title = "Hello")
boxlayout1.add_widget(toolbar)
boxlayout2 = MDBoxLayout()
boxlayout1.add_widget(boxlayout2)
from kivymd.uix.navigationrail import MDNavigationRail, MDNavigationRailItem
navigationrail = MDNavigationRail()
navigationrail.add_widget(MDNavigationRailItem(icon="access-point"))
boxlayout2.add_widget(navigationrail)
return boxlayout1
root = MyApp()
root.run()
【问题讨论】:
【参考方案1】:您必须将对象 navigationrail 作为 MDNavigationRailItem 的参数传递。
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.uix.toolbar import MDToolbar
from kivy.utils import get_color_from_hex
class MyApp(MDApp):
def build(self):
boxlayout1 = MDBoxLayout(orientation = "vertical")
toolbar = MDToolbar(title = "Hello")
boxlayout1.add_widget(toolbar)
boxlayout2 = MDBoxLayout()
boxlayout1.add_widget(boxlayout2)
from kivymd.uix.navigationrail import MDNavigationRail, MDNavigationRailItem
navigationrail = MDNavigationRail(
md_bg_color = get_color_from_hex("#344954"),
# color_normal = get_color_from_hex("#718089"), #crash the app when clicking on an item, don't understand why...
color_active = get_color_from_hex("#f3ab44"),
visible = "Persistent")
for i in range(3):
item = MDNavigationRailItem(navigation_rail = navigationrail, text="item%d" %(i+1))
navigationrail.add_widget(item)
boxlayout2.add_widget(navigationrail)
return boxlayout1
root = MyApp()
root.run()
【讨论】:
请解释一下代码的作用和它是怎么做的。以上是关于如何在没有 KV 语言的情况下使用 MDNavigationRail + MDNavigationRailItem的主要内容,如果未能解决你的问题,请参考以下文章