我想在kivy(kv)中做一个非常简单的例子如下:
on_release:
app.root.ids.scr_mngr.current = 'screen1'
这将失败,因为left_action_items和right_action_items都需要一对对象列表:[name_of_icon,expression]。另一方面,当您处理按钮时,如果我们执行以下操作,该声明将是合法的:
left_action_items: [['arrow-left', lambda x: app.root.ids.scr_mngr.current = 'screen1' ]]
另一方面,left_action_item的正确方法如下:
select *,
(Select top 1 BREAK_M
from sampleTable
where Item_ID <= T.Item_ID
and Break_M is not null
order by item_ID desc
) as LIKETHIS
from sampleTable T
order by item_ID
但这不合法,因为你无法在python下的lambda中执行这样的分配。
left_action_items更改屏幕的方法是什么?
答案 0 :(得分:2)
这是我发现单击MDToolbar图标更改屏幕的最简单方法:
main.py
from kivymd.app import MDApp
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.lang import Builder
Builder.load_file("telas.kv")
class Tela1(Screen):
pass
class Tela2(Screen):
pass
class MainApp(MDApp):
def build(self):
self.sm = ScreenManager(transition=NoTransition())
self.sm.add_widget(Tela1(name="tela1"))
self.sm.add_widget(Tela2(name="tela2"))
return self.sm
def change_screen(self, tela):
self.sm.current = tela
if __name__ == "__main__":
MainApp().run()
telas.kv
<Tela1>:
BoxLayout:
orientation: "vertical"
MDToolbar:
title: "My App"
MDRoundFlatButton:
text: "Go to Tela 2"
on_release: app.root.current = "tela2"
MDLabel:
text: "Tela 1"
<Tela2>:
BoxLayout:
orientation: "vertical"
MDToolbar:
title: "Tela 2"
left_action_items: [["arrow-left", lambda x: app.change_screen("tela1")]]
MDLabel:
text: "Tela 2"
答案 1 :(得分:1)
你可以将你的根类变成python类,并在那里有一个change_screen方法。还要将您的screenmanager设置为根类中的ObjectProperty 然后在kv中使用partial能够将参数传递给方法 试试这样:
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivymd.theming import ThemeManager
class MyLayout(BoxLayout):
scr_mngr = ObjectProperty(None)
def change_screen(self, screen, *args):
self.scr_mngr.current = screen
KV = """
#:import Toolbar kivymd.toolbar.Toolbar
#:import partial functools.partial
MyLayout:
scr_mngr: scr_mngr
orientation: 'vertical'
Toolbar:
id: toolbar
title: 'My Toolbar'
left_action_items: [['arrow-left', partial(root.change_screen, 'screen1') ]]
right_action_items: [['arrow-right', partial(root.change_screen, 'screen2') ]]
ScreenManager:
id: scr_mngr
Screen:
name: 'screen1'
Toolbar:
title: "Screen 1"
Screen:
name: 'screen2'
Toolbar:
title: "Screen 2"
"""
class MyApp(App):
theme_cls = ThemeManager()
def build(self):
return Builder.load_string(KV)
MyApp().run()
答案 2 :(得分:1)
有多种选择,你可以做到
left_action_items: [('arrow-left', (app.root.ids.scr_mngr, 'current', 'screen1'))]
以后再做:
for icon, expr in self.left_action_items:
setattr(*expr)
如果你真的想要一个可执行的表达式,你可以这样做:
left_action_items: [('arrow-left', lambda: setattr(app.root.ids.scr_mngr, 'current' 'screen1'))]
答案 3 :(得分:0)
还有另一种方法。我使用的是:
left_action_items: [['arrow-left', lambda x: root.manager.change_screen("main_screen")]]
屏幕管理器内部功能change_screen()的实现:
def change_screen(self, screen):
# the same as in .kv: app.root.current = screen
self.current = screen