如何从屏幕管理器在 kivymd 工具栏中进行回调?
Posted
技术标签:
【中文标题】如何从屏幕管理器在 kivymd 工具栏中进行回调?【英文标题】:How to do callback in kivymd toolbar from the screen manager? 【发布时间】:2020-12-25 00:50:06 【问题描述】:当我按下工具栏图标时,我试图改变屏幕,但 kivy 说 str 对象不可调用。我该如何解决? (我明白,问题出在语法上,请帮忙)
from kivy.lang import Builder
from kivymd.app import MDApp
KV = '''
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"
MDToolbar:
id: toolbar
pos_hint: "top": 1
elevation: 10
title: "MDNavigationDrawer"
left_action_items: [["arrow-left", lambda x: screen_manager.current("scr 1")]]
MDLabel:
text: "Screen 2"
halign: "center"
MDNavigationDrawer:
id: nav_drawer
screen_manager: screen_manager
nav_drawer: nav_drawer
ScrollView:
MDList:
OneLineListItem:
text: "Screen 1"
on_press: self.parent.parent.parent.nav_drawer.set_state("close") self.parent.parent.parent.screen_manager.current = "scr 1"
OneLineListItem:
text: "Screen 2"
on_press: self.parent.parent.parent.nav_drawer.set_state("close") self.parent.parent.parent.screen_manager.current = "scr 2"
'''
class TestNavigationDrawer(MDApp):
def build(self):
return Builder.load_string(KV)
TestNavigationDrawer().run()
TypeError: 'str' 对象不可调用
【问题讨论】:
【参考方案1】:我认为问题出在scr 1
中的空格,请改用scr1
或scr_1
试试这个
left_action_items: [["arrow-left", lambda x: root.manager.change_screen("scr1")]]
并在您的main.py
中添加此功能
def change_screen(self, screen):
# the same as in .kv: app.root.current = screen
self.current = screen
【讨论】:
很遗憾没有,而且我的网名有 str 值。屏幕:名称:“scr 1” 不起作用。问题总是一样的(((我添加了整个代码【参考方案2】:我找到了可行的解决方案。 也许它会对某人有所帮助:
/main.py
class App(MDApp):
kv_file = 'main.kv'
if __name__ == '__main__':
app = App()
app.run()
/main.kv
<Scr2@Screen>
name: 'scr2'
MDBoxLayout:
orientation: 'vertical'
MDToolbar:
title: 'MDToolbar'
left_action_items: [['arrow-left', lambda _: setattr(root.manager, 'current', 'scr1')]]
MDLabel:
text: 'Content'
halign: 'center'
【讨论】:
以上是关于如何从屏幕管理器在 kivymd 工具栏中进行回调?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 KivyMD (Python) 中结合导航抽屉和多个屏幕?