kivymd 中的 AssertionError
Posted
技术标签:
【中文标题】kivymd 中的 AssertionError【英文标题】:AssertionError in the kivymd 【发布时间】:2021-08-13 16:05:55 【问题描述】:我试图在屏幕管理器中添加屏幕,但在屏幕管理器中分配导航抽屉时出现断言错误。
这是我面临的错误: self._apply_rule( _apply_rule 中的文件“/home/hp/.local/lib/python3.8/site-packages/kivy/lang/builder.py”,第 559 行 断言(规则不在 self.rulectx 中) 断言错误
这是我的代码:
from kivymd.app import MDApp
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
screen_helper = """
ScreenManager:
MenuScreen:
ProfileScreen:
ContentNavigationDrawer:
<MenuScreen>:
name: 'menu'
MDRectangleFlatButton:
text: 'Profile'
pos_hint: 'center_x':0.5,'center_y':0.6
on_press: root.manager.current = 'profile'
MDRectangleFlatButton:
text: 'Upload'
pos_hint: 'center_x':0.5,'center_y':0.5
on_press: root.manager.current = 'upload'
<ProfileScreen>:
name: 'profile'
MDLabel:
text: 'Profile'
halign: 'center'
MDRectangleFlatButton:
text: 'Back'
pos_hint: 'center_x':0.5,'center_y':0.1
on_press: root.manager.current = 'menu'
<ContentNavigationDrawer>:
name : 'upload'
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")]]
NavigationLayout:
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 MenuScreen(Screen):
pass
class ProfileScreen(Screen):
pass
class ContentNavigationDrawer(Screen):
screen_manager = ObjectProperty()
nav_drawer = ObjectProperty()
# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(ProfileScreen(name='profile'))
sm.add_widget(ContentNavigationDrawer(name='upload'))
class DemoApp(MDApp):
def build(self):
screen = Builder.load_string(screen_helper)
return screen
DemoApp().run()
【问题讨论】:
【参考方案1】:我认为问题在于您在screen_helper
中的规则:
<ContentNavigationDrawer>:
包括:
ContentNavigationDrawer:
screen_manager: screen_manager
nav_drawer: nav_drawer
该规则组合告诉 kivy,每当它创建一个 ContentNavigationDrawer
时,它应该创建另一个 ContentNavigationDrawer
作为第一个的孩子。然后它会尝试再次应用原始<ContentNavigationDrawer>:
,创建第三个ContentNavigationDrawer
,再次应用规则创建第四个,依此类推。这将创建一个无限循环。 Kivy 使用assertion
来避免此类循环。所以,你不能使用会创建这样一个循环的规则。
【讨论】:
以上是关于kivymd 中的 AssertionError的主要内容,如果未能解决你的问题,请参考以下文章