Python | ScreenManager en Kivy usando el archivo .kv

Kivy es una herramienta GUI independiente de la plataforma en Python. Como se puede ejecutar en Android, IOS, Linux y Windows, etc. Básicamente se usa para desarrollar la aplicación de Android, pero eso no significa que no se pueda usar en aplicaciones de escritorio.
 

Widget de administrador de pantalla:

El administrador de pantalla es un widget que se utiliza para administrar múltiples pantallas para su aplicación. El ScreenManager predeterminado muestra solo una pantalla a la vez y usa una TransitionBase para cambiar de una pantalla a otra. Se admiten múltiples transiciones.
Se importan las clases ScreenManager y Screen. El ScreenManager se utilizará para la raíz como:
 

from kivy.uix.screenmanager import ScreenManager, Screen

Nota: El ScreenManager.transition predeterminado es una SlideTransition con opciones de dirección y duración.
 

Basic Approach:
1) import kivy
2) import kivyApp
3) import Screen Manager, Screen, ""Transitions you want to use"" 
4) Set minimum version(optional)
5) Create Different Screen classes and pass them
6) Create features of Screen classes in .kv file 
       :: Add features in different screens
7) Create App class
8) return screen manager
9) Run an instance of the class

A continuación se muestra la implementación del código con el archivo .kv en el archivo .py.
 

Python3

# Program to Show how to create a switch
# import kivy module   
import kivy 
      
# base Class of your App inherits from the App class.   
# app:always refers to the instance of your application  
from kivy.app import App
    
# this restrict the kivy version i.e 
# below this kivy version you cannot 
# use the app or software 
kivy.require('1.9.0')
 
# Builder is used when .kv file is
# to be used in .py file
from kivy.lang import Builder
 
# The screen manager is a widget
# dedicated to managing multiple screens for your application.
from kivy.uix.screenmanager import ScreenManager, Screen
  
# You can create your kv code in the Python file
Builder.load_string("""
<ScreenOne>:
    BoxLayout:
        Button:
            text: "Go to Screen 2"
            background_color : 0, 0, 1, 1
            on_press:
                # You can define the duration of the change
                # and the direction of the slide
                root.manager.transition.direction = 'left'
                root.manager.transition.duration = 1
                root.manager.current = 'screen_two'
  
<ScreenTwo>:
    BoxLayout:
        Button:
            text: "Go to Screen 3"
            background_color : 1, 1, 0, 1
            on_press:
                root.manager.transition.direction = 'left'
                root.manager.transition.duration = 1
                root.manager.current = 'screen_three'
 
<ScreenThree>:
    BoxLayout:
        Button:
            text: "Go to Screen 4"
            background_color : 1, 0, 1, 1
            on_press:
                root.manager.transition.direction = 'left'
                root.manager.transition.duration = 1
                root.manager.current = 'screen_four'
 
<ScreenFour>:
    BoxLayout:
        Button:
            text: "Go to Screen 5"
            background_color : 0, 1, 1, 1
            on_press:
                root.manager.transition.direction = 'left'
                root.manager.transition.duration = 1
                root.manager.current = 'screen_five'
 
<ScreenFive>:
    BoxLayout:
        Button:
            text: "Go to Screen 1"
            background_color : 1, 0, 0, 1
            on_press:
                root.manager.transition.direction = 'right'
                root.manager.current = 'screen_one'
 
 
""")
  
# Create a class for all screens in which you can include
# helpful methods specific to that screen
class ScreenOne(Screen):
    pass
  
class ScreenTwo(Screen):
    pass
 
class ScreenThree(Screen):
    pass
 
class ScreenFour(Screen):
    pass
 
class ScreenFive(Screen):
    pass
  
  
# The ScreenManager controls moving between screens
screen_manager = ScreenManager()
  
# Add the screens to the manager and then supply a name
# that is used to switch screens
screen_manager.add_widget(ScreenOne(name ="screen_one"))
screen_manager.add_widget(ScreenTwo(name ="screen_two"))
screen_manager.add_widget(ScreenThree(name ="screen_three"))
screen_manager.add_widget(ScreenFour(name ="screen_four"))
screen_manager.add_widget(ScreenFive(name ="screen_five"))
 
# Create the App class
class ScreenApp(App):
    def build(self):
        return screen_manager
 
# run the app
sample_app = ScreenApp()
sample_app.run()

Producción: 
 

Cambio de transiciones:
 

Tiene varias transiciones disponibles de forma predeterminada, como: 
 

  • NoTransition : cambia de pantalla al instante sin animación
  • SlideTransition : desliza la pantalla hacia adentro o hacia afuera, desde cualquier dirección
  • CardTransition : la nueva pantalla se desliza sobre la anterior o la anterior se desliza sobre la nueva según el modo
  • SwapTransition : implementación de la transición de intercambio de iOS
  • FadeTransition : sombreador para atenuar la entrada/salida de la pantalla
  • WipeTransition : shader para limpiar las pantallas de derecha a izquierda
  • FallOutTransition : sombreador donde la pantalla antigua ‘cae’ y se vuelve transparente, revelando la nueva detrás de ella.
  • RiseInTransition : sombreador donde la nueva pantalla se eleva desde el centro de la pantalla mientras se desvanece de transparente a opaco.

Puede cambiar fácilmente las transiciones cambiando la propiedad ScreenManager.transition: 
 

sm = ScreenManager(transition=FadeTransition())

Python3

# Program to Show how to create a switch
# import kivy module   
import kivy 
      
# base Class of your App inherits from the App class.   
# app:always refers to the instance of your application  
from kivy.app import App
    
# this restrict the kivy version i.e 
# below this kivy version you cannot 
# use the app or software 
kivy.require('1.9.0')
 
# Builder is used when .kv file is
# to be used in .py file
from kivy.lang import Builder
 
# The screen manager is a widget
# dedicated to managing multiple screens for your application.
from kivy.uix.screenmanager import (ScreenManager, Screen, NoTransition,
SlideTransition, CardTransition, SwapTransition,
FadeTransition, WipeTransition, FallOutTransition, RiseInTransition)
  
# You can create your kv code in the Python file
Builder.load_string("""
<ScreenOne>:
    BoxLayout:
        Button:
            text: "Go to Screen 2"
            background_color : 0, 0, 1, 1
            on_press:
                # You can define the duration of the change
                # and the direction of the slide
                root.manager.transition.direction = 'left'
                root.manager.transition.duration = 1
                root.manager.current = 'screen_two'
  
<ScreenTwo>:
    BoxLayout:
        Button:
            text: "Go to Screen 3"
            background_color : 1, 1, 0, 1
            on_press:
                root.manager.transition.direction = 'left'
                root.manager.transition.duration = 1
                root.manager.current = 'screen_three'
 
<ScreenThree>:
    BoxLayout:
        Button:
            text: "Go to Screen 4"
            background_color : 1, 0, 1, 1
            on_press:
                root.manager.transition.direction = 'left'
                root.manager.transition.duration = 1
                root.manager.current = 'screen_four'
 
<ScreenFour>:
    BoxLayout:
        Button:
            text: "Go to Screen 5"
            background_color : 0, 1, 1, 1
            on_press:
                root.manager.transition.direction = 'left'
                root.manager.transition.duration = 1
                root.manager.current = 'screen_five'
 
<ScreenFive>:
    BoxLayout:
        Button:
            text: "Go to Screen 1"
            background_color : 1, 0, 0, 1
            on_press:
                root.manager.transition.direction = 'right'
                root.manager.current = 'screen_one'
 
 
""")
  
# Create a class for all screens in which you can include
# helpful methods specific to that screen
class ScreenOne(Screen):
    pass
  
class ScreenTwo(Screen):
    pass
 
class ScreenThree(Screen):
    pass
 
class ScreenFour(Screen):
    pass
 
class ScreenFive(Screen):
    pass
  
  
# The ScreenManager controls moving between screens
# You can change the transitions accordingly
screen_manager = ScreenManager(transition = RiseInTransition())
  
# Add the screens to the manager and then supply a name
# that is used to switch screens
screen_manager.add_widget(ScreenOne(name ="screen_one"))
screen_manager.add_widget(ScreenTwo(name ="screen_two"))
screen_manager.add_widget(ScreenThree(name ="screen_three"))
screen_manager.add_widget(ScreenFour(name ="screen_four"))
screen_manager.add_widget(ScreenFive(name ="screen_five"))
 
# Create the App class
class ScreenApp(App):
    def build(self):
        return screen_manager
 
# run the app
sample_app = ScreenApp()
sample_app.run()

Nota: el código es el mismo, se agregan algunos puntos en el código, no se confunda.
Video de salida de diferentes transiciones – 
 

Publicación traducida automáticamente

Artículo escrito por YashKhandelwal8 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *