当我按下工具栏图标时,我试图更改屏幕,但是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”对象不可调用
答案 0 :(得分:0)
我认为问题是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
答案 1 :(得分:0)
我找到了可行的解决方案。 也许它会对某人有所帮助:
/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'