kivy
  1. kivy-switching-between-screens

Switching Between Screens - Screen Navigation in Kivy

Screen navigation in Kivy allows us to switch between different screens in a Kivy application. This is useful for creating multi-screen applications, where each screen displays different content and functionality.

Syntax

<ScreenManager>:
    ScreenOne:
        name: "screen_one"
    ScreenTwo:
        name: "screen_two"
    
<ScreenOne>:
    name: "screen_one"
    # ScreenOne content here
    
<ScreenTwo>:
    name: "screen_two"
    # ScreenTwo content here

Example

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager

class ScreenOne(Screen):
    pass

class ScreenTwo(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

class SwitchScreenApp(App):
    def build(self):
        sm = ScreenManagement()
        sm.add_widget(ScreenOne(name='screen_one'))
        sm.add_widget(ScreenTwo(name='screen_two'))

        return sm

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

Output

When running the above example, you should see a Kivy application with two screens. The first screen should have the name "screen_one" and the second screen should have the name "screen_two". Switching between the screens should be possible by clicking on a button that triggers a function that switches between the two screens.

Explanation

The ScreenManager is the main element that handles the navigation between screens. Inside the ScreenManager we define the different screens that we want to display. Each screen has a name attribute that is used to reference the screen when switching between screens.

The SwitchScreenApp class defines the Kivy application. In the build method, we create an instance of the ScreenManagement class, which is a subclass of ScreenManager. We then create instances of the ScreenOne and ScreenTwo classes and add them to the ScreenManagement instance using the add_widget method.

Use

Screen navigation is useful in any mobile or desktop app that has more than one logical screen. For example, in a mobile app that has a sign in screen and a main dashboard screen, screen navigation would be used to switch between the two screens.

Important Points

  • Screen navigation is achieved using the ScreenManager in Kivy.
  • Screens are defined as separate classes that are added to the ScreenManager using the add_widget method.
  • Each screen has a name attribute that is used to reference the screen when switching between screens.
  • Screen navigation can be triggered by a button or other widget that has a function that calls the ScreenManager's current method to switch to a new screen.

Summary

Screen navigation in Kivy allows us switch between different screens in a Kivy application. It is achieved using the ScreenManager class and separate Screen classes for each screen we want display. Screen navigation is useful in any mobile or app that has more than one logical screen.

Published on: