Kivy:如何在不同类中定义的接口之间切换



我正在开发Kivy/KivyMD - Python应用程序。我在三个不同的类中定义了三个不同的UI。每个界面都包含一个按钮来在它们之间切换。当应用程序启动时,显示第一个界面。下面是代码:

from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.relativelayout import MDRelativeLayout
Builder.load_string(
"""   
<View3>:
MDRaisedButton:
text: 'GO TO VIEW 1'
pos_hint: {'center_x': 0.7, 'center_y': 0.7}
#on_release:

<View2>:
MDRaisedButton:
text: 'GO TO VIEW 3'
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
#on_release:


<View1>:
MDRaisedButton:
text: 'GO TO VIEW 2'
pos_hint: {'center_x': 0.3, 'center_y': 0.3}
#on_release: 

"""
)


class View3(MDRelativeLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)

class View2(MDRelativeLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)      

class View1(MDRelativeLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)

class MainApp(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.view = View1()
def build(self):
return View1()

if __name__ == '__main__':
MainApp().run()

我如何在它们之间切换?

我自己不使用KivyMD,但您可以使用ScreenManagerScreen(查看文档)。

的例子:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
Builder.load_string(
"""   
<View3>:
Button:
text: 'GO TO VIEW 1'
pos_hint: {'center_x': 0.7, 'center_y': 0.7}
on_release: root.manager.current = 'view1'

<View2>:
Button:
text: 'GO TO VIEW 3'
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
on_release: root.manager.current = 'view3'

<View1>:
Button:
text: 'GO TO VIEW 2'
pos_hint: {'center_x': 0.3, 'center_y': 0.3}
on_release: root.manager.current = 'view2'
"""
)

class View3(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)

class View2(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)

class View1(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)

class MainApp(App):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.sm = ScreenManager()
self.sm.add_widget(View1(name="view1"))
self.sm.add_widget(View2(name="view2"))
self.sm.add_widget(View3(name="view3"))
def build(self):
return self.sm

if __name__ == '__main__':
MainApp().run()

您可以使用ScreenManager.current属性更改视图,或者从kv更改root.manager.current属性。

请注意,KivyMD有对应的小部件:MDScreenManagerMDScreen,所以您也可以使用它们。

还要注意,这些屏幕已经继承自RelativeLayout。如果您确实需要使用其他布局,我建议将其添加到kv中。

相关内容

  • 没有找到相关文章

最新更新