kivy学习笔记-ScreenManager实现GUI界面切换

使用kivy库提供的ScreenManager对象可以快速的实现GUI界面切换。以下为代码实例:

# file name:screen.kv
: 
    Button:
        text:"Enter sub View"
        size_hint: None, None
        pos_hint: {'right': 1,'top':1}
        size: 150, 50
        on_press:root.manager.current="sub"
    Label:
        size_hint: None, None
        pos_hint: {'left': 1,'top':1}
        size: 150, 50
        text:"Main"

:
    Button:
        size_hint: None, None
        pos_hint: {'right': 1,'top':1}
        size: 150, 50
        text:"Return"
        on_press:root.manager.current="main"
    Label:
        text:"Sub"
        size_hint: None, None
        pos_hint: {'left': 1,'top':1}
        size: 150, 50
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.factory import Factory
from kivy.uix.screenmanager import ScreenManager, Screen

class MainScreen(Screen):
    pass

class SubScreen(Screen):
    pass


class ScreenApp(App): 
    
    def build(self):
        sm = ScreenManager()
        scm = MainScreen(name="main")
        scs = SubScreen(name="sub")
        sm.add_widget(scm)
        sm.add_widget(scs)
        return sm

ScreenApp().run()
注意Screen的布局方式为RelativeLayout。

运行界面图如下:

kivy学习笔记-ScreenManager实现GUI界面切换_第1张图片

kivy学习笔记-ScreenManager实现GUI界面切换_第2张图片

你可能感兴趣的:(python,IT萌新)