Python | Cambiar widget en Kivy

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.
 

????????? Tutorial de Kivy: aprenda Kivy con ejemplos .

Cambiar widget:

El widget Switch está activo o inactivo, como un interruptor de luz mecánico. El usuario puede deslizar hacia la izquierda/derecha para activarlo/desactivarlo. El valor representado por el interruptor es Verdadero o Falso. Es decir, el interruptor puede estar en la posición de encendido o en la posición de apagado .
Para trabajar con Switch debes tener que importar: 
 

from kivy.uix.switch import Switch

Nota: si desea controlar el estado con un solo toque en lugar de deslizar el dedo, utilice el ToggleButton en su lugar.
 

Basic Approach:

1) import kivy
2) import kivyApp
3) import Switch
4) import Gridlayout
5) import Label
6) Set minimum version(optional)
7) create Layout class(In this you create a switch)
8) create App class
9) return Layout/widget/Class(according to requirement)
10) Run an instance of the class

Implementación del Enfoque: 
 

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')
 
# The Switch widget is active or inactive
# The state transition of a switch is from
# either on to off or off to on.
from kivy.uix.switch import Switch
 
# The GridLayout arranges children in a matrix.
# It takes the available space and
# divides it into columns and rows,
# then adds widgets to the resulting “cells”.
from kivy.uix.gridlayout import GridLayout
 
# The Label widget is for rendering text.
from kivy.uix.label import Label
 
# A Gridlayout with a label a switch
# A class which contains all stuff about the switch
class SimpleSwitch(GridLayout):
 
     # Defining __init__ constructor
     def __init__(self, **kwargs):
 
          # super function can be used to gain access
          # to inherited methods from a parent or sibling class
          # that has been overwritten in a class object.
          super(SimpleSwitch, self).__init__(**kwargs)
 
          # no of columns
          self.cols = 2
 
          # Adding label to the Switch
          self.add_widget(Label(text ="Switch"))
 
          # Initially switch is Off i.e active = False
          self.settings_sample = Switch(active = False)
 
          # Add widget
          self.add_widget(self.settings_sample)
 
            
# Defining the App Class
class SwitchApp(App):
     # define build function
     def build(self):
          # return the switch class
          return SimpleSwitch()
 
  
# Run the kivy app
if __name__ == '__main__':
     SwitchApp().run()

Producción: 
 

Adjuntar devolución de llamada al conmutador: 
 

  • Se puede conectar un interruptor con una devolución de llamada para recuperar el valor del interruptor.
  • La transición de estado de un interruptor es de ENCENDIDO a APAGADO o de APAGADO a ENCENDIDO.
  • Cuando el interruptor realiza cualquier transición, se activa la devolución de llamada y se puede recuperar el nuevo estado, es decir, vino y se puede realizar cualquier otra acción en función del estado.
  • Por defecto, la representación del widget es estática. El tamaño mínimo requerido es de 83*32 píxeles.
  • Todo el widget está activo, no solo la parte con gráficos. Siempre que deslice el dedo sobre el cuadro delimitador del widget, funcionará.

Ahora, para adjuntar una devolución de llamada, debe definir una función de devolución de llamada y vincularla con el interruptor. A continuación se muestra el código de cómo adjuntar una devolución de llamada:
 

Python3

# Program to Show how to attach a callback to 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')
 
# The Switch widget is active or inactive
# The state transition of a switch is from
# either on to off or off to on.
from kivy.uix.switch import Switch
 
# The GridLayout arranges children in a matrix.
# It takes the available space and
# divides it into columns and rows,
# then adds widgets to the resulting “cells”.
from kivy.uix.gridlayout import GridLayout
 
# The Label widget is for rendering text.
from kivy.uix.label import Label
 
# A Gridlayout with a label a switch
# A class which contains all stuff about the switch
class SimpleSwitch(GridLayout):
 
     # Defining __init__ constructor
     def __init__(self, **kwargs):
 
          # super function can be used to gain access
          # to inherited methods from a parent or sibling class
          # that has been overwritten in a class object.
          super(SimpleSwitch, self).__init__(**kwargs)
 
          # no of columns
          self.cols = 2
 
          # Adding label to the Switch
          self.add_widget(Label(text ="Switch"))
 
          # Initially switch is Off i.e active = False
          self.settings_sample = Switch(active = False)
 
          # Add widget
          self.add_widget(self.settings_sample)
 
          # Arranging a callback to the switch
          # using bing function
          self.settings_sample.bind(active = switch_callback)      
 
# Callback for the switch state transition
# Defining a Callback function
# Contains Two parameter switchObject, switchValue
def switch_callback(switchObject, switchValue):
     
    # Switch value are True and False
    if(switchValue):
        print('Switch is ON:):):)')
    else:
        print('Switch is OFF:(:(:(')
 
  
# Defining the App Class
class SwitchApp(App):
     # define build function
     def build(self):
          # return the switch class
          return SimpleSwitch()
 
  
# Run the kivy app
if __name__ == '__main__':
     SwitchApp().run()

Producción: 
 

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 *