Kivy: Changing screens in screen manager with an on_press event

后端 未结 3 1036
旧时难觅i
旧时难觅i 2020-12-10 14:55

I would like to know how to change screens using an on_press event binded to a button, without using a KV file/KV language.

I have read through the Kivy documentatio

3条回答
  •  春和景丽
    2020-12-10 15:51

    One simple way to accomplish this is to define your own button subclass:

    class ScreenButton(Button):
        screenmanager = ObjectProperty()
        def on_press(self, *args):
            super(ScreenButton, self).on_press(*args)
            self.screenmanager.current = 'whatever'
    

    The on_press method is automatically called when the button is pressed, so the screenmanager's current property will be changed.

    Then you can have code something like:

    sm = ScreenManager()
    
    sc1 = Screen(name='firstscreen')
    sc1.add_widget(ScreenButton(screenmanager=sm))
    
    sc2 = Screen(name='whatever')
    sc2.add_widget(Label(text='another screen'))
    
    sm.add_widget(sc1)
    sm.add_widget(sc2)
    

    Clicking the button should switch the screens as required.

    Another way (which is probably how kv language actually does it) would be to manually use the bind method.

    def switching_function(*args):
        some_screen_manager.current = 'whatever'
    
    some_button.bind(on_press=switching_function)
    

    This would mean that switching_function is called whenever some_button is pressed. Of course there is a lot of flexibility here regarding how and when you define the function, so (for instance) you could do something more general like pass the screenmanager as the first argument to the function.

    I didn't test this code and it isn't a complete app, but hopefully the meaning is clear. Either method should work fine, you can choose the way that seems most sensible. I might construct a more complete example later.

提交回复
热议问题