Kivy Es
Kivy Es
#kivy
Tabla de contenido
Acerca de 1
Observaciones 2
Examples 2
Instalación y configuración 2
Windows 2
Caminos 4
Simplificarlo 4
RecycleView 7
Capítulo 2: Propiedad 13
Examples 13
Observaciones 16
Importaciones circulares 16
Examples 16
Gestor de pantalla 18
Creditos 20
Acerca de
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: kivy
It is an unofficial and free kivy ebook created for educational purposes. All the content is extracted
from Stack Overflow Documentation, which is written by many hardworking individuals at Stack
Overflow. It is neither affiliated with Stack Overflow nor official kivy.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/es/home 1
Capítulo 1: Empezando con Kivy
Observaciones
Kivy es una biblioteca de código abierto de Python para el rápido desarrollo de interfaces de
usuario multiplataforma. Las aplicaciones Kivy se pueden desarrollar para Linux, Windows, OS X,
Android e iOS usando el mismo código base.
Desarrollar interfaces en Kivy opcionalmente implica el uso de kvlang, un pequeño lenguaje que
admite expresiones similares a python e interoperabilidad de python. El uso de kvlang puede
simplificar drásticamente el desarrollo de la interfaz de usuario en comparación con el uso
exclusivo de Python.
Kivy es de uso gratuito (actualmente bajo la licencia MIT) y cuenta con respaldo profesional.
Examples
Instalación y configuración
Windows
Hay dos opciones de cómo instalar Kivy:
Aunque Kivy ya tiene proveedores de audio y video, GStreamer es necesario para cosas más
avanzadas.
Para hacerlo más simple, <python> en el siguiente texto significa una ruta al directorio con el
archivo python.exe .
1. Rueda
https://riptutorial.com/es/home 2
El paquete de la rueda proporciona Kivy compilado, pero con los componentes de fuente de
cython eliminados, lo que significa que el código del núcleo no se puede compilar de esta
manera. El código de Python, sin embargo, es editable.
La última versión del repositorio oficial está disponible a través de ruedas construidas todas
las noches en google drive. Visita el enlace en documentos que coinciden con tu versión de
python. Después de descargar una rueda adecuada, renómbrela para que coincida con el
formato de este ejemplo y ejecute el comando.
2. Fuente
Hay más dependencias necesarias para instalar Kivy desde la fuente que para usar las
ruedas, pero la instalación es más flexible.
[build]
compiler = mingw32
No olvide configurar las variables de entorno para que Kivy sepa qué proveedores debería
usar.
set USE_SDL2=1
set USE_GSTREAMER=1
Consulte la sección Paths para asegurarse de que todo esté configurado correctamente e
instale Kivy. Elija una de estas opciones:
https://riptutorial.com/es/home 3
Caminos
Kivy necesita un acceso a los binarios de algunas dependencias. Esto significa que las carpetas
correctas deben estar en la variable PATH del entorno.
set PATH=<python>\Tools;<python>\Scripts;<python>\share\sdl2\bin;%PATH%
De esta manera, el IDE IDE de Python puede incluirse en la ruta con <python>\Lib\idlelib; .
Luego escriba idle en la consola e IDLE estará listo para usar Kivy.
Simplificarlo
Para evitar la configuración repetitiva de las variables de entorno, establezca cada ruta necesaria
de esta manera o haga un archivo por lotes ( .bat ) con estas líneas ubicadas en <python> :
set PATH=%~dp0;%~dp0Tools;%~dp0Scripts;%~dp0share\sdl2\bin;%~dp0Lib\idlelib;%PATH%
cmd.exe
Para ejecutar el proyecto Kivy después de la instalación, ejecute cmd.exe o el archivo por lotes y
use python <filename>.py
instalación en Ubuntu
Para instalar kivy en ubuntu con el ejemplo kivy, abra el terminal y ejecute el siguiente comando
El siguiente ejemplo crea un lienzo con 2 puntos y 1 línea en medio. Podrás mover el punto y la
línea alrededor.
class CustomLayout(BoxLayout):
https://riptutorial.com/es/home 4
def __init__(self, **kwargs):
super(CustomLayout, self).__init__(**kwargs)
self.canvas_edge = {}
self.canvas_nodes = {}
self.nodesize = [25, 25]
self.grabbed = {}
#declare a canvas
with self.canvas.after:
pass
self.define_nodes()
self.canvas.add(self.canvas_nodes[0])
self.canvas.add(self.canvas_nodes[1])
self.define_edge()
self.canvas.add(self.canvas_edge)
def define_nodes(self):
"""define all the node canvas elements as a list"""
self.canvas_nodes[0] = Ellipse(
size = self.nodesize,
pos = [100,100]
)
self.canvas_nodes[1] = Ellipse(
size = self.nodesize,
pos = [200,200]
)
def define_edge(self):
"""define an edge canvas elements"""
self.canvas_edge = Line(
points = [
self.canvas_nodes[0].pos[0] + self.nodesize[0] / 2,
self.canvas_nodes[0].pos[1] + self.nodesize[1] / 2,
self.canvas_nodes[1].pos[0] + self.nodesize[0] / 2,
self.canvas_nodes[1].pos[1] + self.nodesize[1] / 2
],
joint = 'round',
cap = 'round',
width = 3
)
https://riptutorial.com/es/home 5
def on_touch_move(self, touch):
if touch.grab_current is self:
self.grabbed.pos = [touch.pos[0] - self.nodesize[0] / 2, touch.pos[1] -
self.nodesize[1] / 2]
self.canvas.clear()
self.canvas.add(self.canvas_nodes[0])
self.canvas.add(self.canvas_nodes[1])
self.define_edge()
self.canvas.add(self.canvas_edge)
else:
# it's a normal touch
pass
class MainApp(App):
def build(self):
root = CustomLayout()
return root
if __name__ == '__main__':
MainApp().run()
El siguiente código ilustra cómo hacer la aplicación 'hello world' en kivy. Para ejecutar esta
aplicación en ios y android, guárdela como main.py y use buildozer.
Builder.load_string('''
<SimpleLabel>:
text: 'Hello World'
''')
class SimpleLabel(Label):
pass
class SampleApp(App):
def build(self):
return SimpleLabel()
if __name__ == "__main__":
SampleApp().run()
https://riptutorial.com/es/home 6
Ejemplo emergente simple en Kivy.
El siguiente código ilustra cómo hacer una ventana emergente simple con Kivy.
Builder.load_string('''
<SimpleButton>:
on_press: self.fire_popup()
<SimplePopup>:
id:pop
size_hint: .4, .4
auto_dismiss: False
title: 'Hello world!!'
Button:
text: 'Click here to dismiss'
on_press: pop.dismiss()
''')
class SimplePopup(Popup):
pass
class SimpleButton(Button):
text = "Fire Popup !"
def fire_popup(self):
pops=SimplePopup()
pops.open()
class SampleApp(App):
def build(self):
return SimpleButton()
SampleApp().run()
RecycleView
items = [
{"color":(1, 1, 1, 1), "font_size": "20sp", "text": "white", "input_data":
["some","random","data"]},
{"color":(.5,1, 1, 1), "font_size": "30sp", "text": "lightblue", "input_data": [1,6,3]},
{"color":(.5,.5,1, 1), "font_size": "40sp", "text": "blue", "input_data": [64,16,9]},
{"color":(.5,.5,.5,1), "font_size": "70sp", "text": "gray", "input_data":
[8766,13,6]},
{"color":(1,.5,.5, 1), "font_size": "60sp", "text": "orange", "input_data": [9,4,6]},
{"color":(1, 1,.5, 1), "font_size": "50sp", "text": "yellow", "input_data":
[852,958,123]}
]
https://riptutorial.com/es/home 7
class MyButton(Button):
def print_data(self,data):
print(data)
KV = '''
<MyButton>:
on_release:
root.print_data(self.input_data)
RecycleView:
data: []
viewclass: 'MyButton'
RecycleBoxLayout:
default_size_hint: 1, None
orientation: 'vertical'
'''
class Test(App):
def build(self):
root = Builder.load_string(KV)
root.data = [item for item in items]
return root
Test().run()
class TutorialApp(App):
def build(self):
return
TutorialApp().run()
Todos los códigos a continuación (excepto los ejemplos 1 y 3) tienen el mismo widget y
características similares, pero muestran una forma diferente de crear la aplicación.
https://riptutorial.com/es/home 8
Ejemplo 2: devolver varios widgets + el botón imprime el texto de la etiqueta
class TutorialApp(App):
def build(self):
mylayout = BoxLayout(orientation="vertical")
mylabel = Label(text= "My App")
mybutton =Button(text="Click me!")
mylayout.add_widget(mylabel)
mybutton.bind(on_press= lambda a:print(mylabel.text))
mylayout.add_widget(mybutton)
return mylayout
TutorialApp().run()
Ejemplo 3: usando una clase (widget único) + el botón imprime "Mi botón"
class Mybutton(Button):
text="Click me!"
on_press =lambda a : print("My Button")
class TutorialApp(App):
def build(self):
return Mybutton()
TutorialApp().run()
Ejemplo 4: es lo mismo que ej. 2 pero muestra como usar una clase
class MyLayout(BoxLayout):
#You don't need to understand these 2 lines to make it work!
def __init__(self, **kwargs):
super(MyLayout, self).__init__(**kwargs)
self.orientation="vertical"
mylabel = Label(text= "My App")
self.add_widget(mylabel)
mybutton =Button(text="Click me!")
mybutton.bind(on_press= lambda a:print(mylabel.text))
self.add_widget(mybutton)
class TutorialApp(App):
def build(self):
return MyLayout()
TutorialApp().run()
https://riptutorial.com/es/home 9
Con lenguaje .kv
Ejemplo 5: lo mismo pero que muestra cómo usar el lenguaje kv dentro de python
En .py:
class MyLayout(BoxLayout):
pass
class TutorialApp(App):
#the kv file name will be Tutorial (name is before the "App")
def build(self):
return MyLayout()
TutorialApp().run()
En Tutorial.kv:
** Ejemplo 7: enlace a un archivo kv específico + una definición en python que recibe el label.text
**
https://riptutorial.com/es/home 10
En .py:
class MyLayout(BoxLayout):
def printMe(self_xx, yy):
print(yy)
class TutorialApp(App):
def build(self):
self.load_kv('myapp.kv')
return MyLayout()
TutorialApp().run()
En myapp.kv: orientación: "vertical" Etiqueta: id: mylabel text: "My App" Button: text: "Click me!"
on_press: root.printMe (mylabel.text)
Ejemplo 8: el botón imprime el texto de la etiqueta (con una definición en python usando
los ids (las "ID"))
En .py:
class MyLayout(BoxLayout):
def printMe(self):
print(self.ids.mylabel.text)
class TutorialApp(App):
def build(self):
self.load_kv('myapp.kv')
return MyLayout()
TutorialApp().run()
En myapp.kv:
<MyLayout>
orientation:"vertical"
Label:
id:mylabel
text:"My App"
Button:
text: "Click me!"
on_press: root.printMe()
Ejemplo 9: el botón imprime el texto de la etiqueta (con una definición en python usando
StringProperty)
En .py:
https://riptutorial.com/es/home 11
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
class MyLayout(BoxLayout):
stringProperty_mylabel= StringProperty("My App")
def printMe(self):
print(self.stringProperty_mylabel)
class TutorialApp(App):
def build(self):
return MyLayout()
TutorialApp().run()
En Tutorial.kv:
<MyLayout>
orientation:"vertical"
Label:
id:mylabel
text:root.stringProperty_mylabel
Button:
text: "Click me!"
on_press: root.printMe()
Ejemplo 10: el botón imprime el texto de la etiqueta (con una definición en python usando
ObjectProperty)
En .py:
class TutorialApp(App):
def build(self):
return MyLayout()
TutorialApp().run()
En Tutorial.kv:
<MyLayout>
orientation:"vertical"
objectProperty_mylabel:mylabel
Label:
id:mylabel
text:"My App"
Button:
text: "Click me!"
on_press: root.printMe()
https://riptutorial.com/es/home 12
Capítulo 2: Propiedad
Examples
Diferencia entre propiedades y vinculación.
En breve:
<Tuto_Property>:
orientation: "vertical"
padding:10,10
spacing: 10
Label:
text: "Press the 3 button (+1) several times and then modify the number in the
TextInput.The first counter (with StringProperty but no binding) doesn't take into account the
change that happened in the app, but the second one does.String Property makes it easy to pass
the update from the python side to the user interface, binding pass the changes that happened
on the user interface to the python side. "
text_size: self.size
padding: 20,20
Property_no_Binding:
Property_with_Binding:
Simple:
<Property_no_Binding>:
spacing: 10
label_ObjectProperty: result
CustLab1:
text: "With Property but no Binding"
CustButton:
https://riptutorial.com/es/home 13
on_press: root.counter_textInput_StringProperty()
CustTextInput:
id:textinput_id
text: root.textInput_StringProperty
CustLab2:
id: result
<Property_with_Binding>:
spacing: 10
label_ObjectProperty: result
CustLab1:
text: "With Property and Binding"
CustButton:
on_press: root.counter_textInput_StringProperty()
CustTextInput:
id:textinput_id
text: root.textInput_StringProperty
on_text: root.textInput_StringProperty = self.text ## this is the binding
CustLab2:
id: result
<Simple>
spacing: 10
CustLab1:
text: "Without Property"
CustButton:
on_press: root.simple(textinput_id, result)
CustTextInput:
id:textinput_id
text: "0"
CustLab2:
id: result
""")
class Property_no_Binding(BoxLayout):
textInput_StringProperty= StringProperty("0")
label_ObjectProperty = ObjectProperty(None)
def counter_textInput_StringProperty(self):
self.label_ObjectProperty.text= ("Before the counter was updated:\n\n
textinput_id.text:" + self.ids.textinput_id.text + "\n\n textInput_StringProperty:" +
self.textInput_StringProperty)
self.textInput_StringProperty =str(int(self.textInput_StringProperty)+1)
class Property_with_Binding(BoxLayout):
textInput_StringProperty= StringProperty("0")
label_ObjectProperty = ObjectProperty(None)
def counter_textInput_StringProperty(self):
self.label_ObjectProperty.text= ("Before the counter was updated:\n\n
textinput_id.text:" + self.ids.textinput_id.text + "\n\n textInput_StringProperty:" +
self.textInput_StringProperty)
self.textInput_StringProperty =str(int(self.textInput_StringProperty)+1)
pass
class Simple(BoxLayout):
def simple(self,textinput_id, result):
result.text = ("Before the counter was updated:\n\nIn the TextInput:" +
textinput_id.text)
textinput_id.text = str(int(textinput_id.text) + 1)
https://riptutorial.com/es/home 14
pass
class Tuto_Property(BoxLayout):
# def counter(self,app):
# print("Stringproperty:",app.numbertext)
# print("ObjectProperty:",self.objproper_number.text)
# print("text:",self.ids.number.text,"\n")
# app.numbertext=str(int(app.numbertext)+1)
MyApp().run()
https://riptutorial.com/es/home 15
Capítulo 3: Usando el administrador de
pantalla
Observaciones
Importaciones circulares
Este es un gran problema en Kivy, Python y muchos lenguajes de programación
Cuando dos recursos requieren un recurso, es normal colocar este recurso en el archivo que más
lo utilizará. Pero si esto sucede con dos recursos, y terminan en archivos opuestos, la importación
de ambos en Python resultará en una importación circular.
Python importará el primer archivo, pero este archivo importará el segundo. En el segundo, esto
importa el primer archivo, que a su vez importa el segundo y así sucesivamente. Python lanza el
error ImportError : cannot import name <classname>
Esto se puede resolver utilizando un tercer archivo e importando este tercer archivo a los dos
primeros. Esto es resources.py en el segundo ejemplo.
Examples
Uso simple del administrador de pantalla
class CustomScreen(Screen):
https://riptutorial.com/es/home 16
# Put a layout in the Screen which will take
# Screen's size and pos.
class ScreenManagerApp(App):
def build(self):
# Get an object of some widget that will be the core
# of the application - in this case ScreenManager
root = ScreenManager()
https://riptutorial.com/es/home 17
# Add 4 CustomScreens with name 'Screen <order>`
for x in range(4):
root.add_widget(CustomScreen(name='Screen %d' % x))
if __name__ == '__main__':
# And run the App with its method 'run'
ScreenManagerApp().run()
Gestor de pantalla
<SettingsScreen>:
BoxLayout:
Button:
text: 'First Button on Settings'
on_press: root.manager.current = 'menu'
Button:
text: 'Second Button on Settings'
""")
class SettingsScreen(Screen):
pass
https://riptutorial.com/es/home 18
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SettingsScreen(name='settings'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
https://riptutorial.com/es/home 19
Creditos
S.
Capítulos Contributors
No
Usando el
3 administrador de KeyWeeUsr, M Ganesh, OllieNye, picibucor
pantalla
https://riptutorial.com/es/home 20