如何获取/传递当前ScreenManager到按钮回调函数? (没有使用的kv文件)

时间:2014-07-25 05:34:14

标签: python-3.x kivy

问题很简单。我有ScreenManager作为sm变量,我如何得到它,屏幕信息到按钮回调。非常感谢您提供可能的解决方案。

以下是我的代码的问题部分,我已经评论了我需要解决的部分:

def build(self):
    def callback_home(dt):
        # How do I get the current sreenmanager here so
        # things would work as below
        sm.switch_to(screen1, direction='left')

    app = FloatLayout()

    # Ui top
    anchor_top = AnchorLayout(anchor_x='center', anchor_y='top')
    app.add_widget(anchor_top)

    box_top = BoxLayout(orientation='horizontal',
                        size_hint=(1.0, 0.1))
    anchor_top.add_widget(box_top)

    btn_home = Button(text='Home')
    btn_home.bind(on_press=callback_home) #Callback line is in here
    btn_add = Button(text='Add')
    btn_upload = Button(text='Upload')

    box_top.add_widget(btn_home)
    box_top.add_widget(btn_add)
    box_top.add_widget(btn_upload)

    # Ui bottom
    anchor_bottom = AnchorLayout(anchor_x='center', anchor_y='bottom')
    app.add_widget(anchor_bottom)

    sm = ScreenManager(size_hint=(1.0, 0.9))
    anchor_bottom.add_widget(sm)

    screen1 = Screen(name='Home')
    screen1.add_widget(Label(text='Home'))
    sm.add_widget(screen1)
    screen2 = Screen(name='Add')
    screen2.add_widget(Label(text='Add'))
    sm.add_widget(screen2)
    screen3 = Screen(name='Upload')
    screen3.add_widget(Label(text='Upload'))
    sm.add_widget(screen3)
    return app

1 个答案:

答案 0 :(得分:0)

创建ScreenManager后定义回调函数。但如果你使用kv语言,这会容易10倍。

此外 - ScreenManager.switch_to()仅适用于新的Screen。使用此方法切换到已添加到Screen的{​​{1}}会抛出ScreenManager

最后,如果您使用Exception而不是BoxLayoutFloatLayout,您的布局会更简单。

AnchorLayout