Empezando con kivy
Toca, agarra y mueve
El siguiente ejemplo crea un lienzo con 2 puntos y 1 línea en el medio. Podrás mover el punto y la línea.
from kivy.app import App
from kivy.graphics import Ellipse, Line
from kivy.uix.boxlayout import BoxLayout
class CustomLayout(BoxLayout):
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
)
def on_touch_down(self, touch):
for key, value in self.canvas_nodes.items():
if (value.pos[0] - self.nodesize[0]) <= touch.pos[0] <= (value.pos[0] + self.nodesize[0]):
if (value.pos[1] - self.nodesize[1]) <= touch.pos[1] <= (value.pos[1] + self.nodesize[1]):
touch.grab(self)
self.grabbed = self.canvas_nodes[key]
return True
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
def on_touch_up(self, touch):
if touch.grab_current is self:
# I receive my grabbed touch, I must ungrab it!
touch.ungrab(self)
else:
# it's a normal touch
pass
class MainApp(App):
def build(self):
root = CustomLayout()
return root
if __name__ == '__main__':
MainApp().run()
Ejemplo emergente simple en Kivy.
El siguiente código ilustra cómo hacer una ventana emergente simple con Kivy.
from kivy.app import App
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.button import Button
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()
Instalación y configuración
ventanas
Hay dos opciones para instalar Kivy:
Primero, asegúrese de que las herramientas de Python estén actualizadas.
python -m pip install --upgrade pip wheel setuptools
Luego instale las dependencias básicas.
python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew
Aunque Kivy ya tiene proveedores de audio y video, se requiere GStreamer para cosas más avanzadas.
python -m pip install kivy.deps.gstreamer --extra-index-url https://kivy.org/downloads/packages/simple/
Para hacerlo más simple, <python>
en el siguiente texto significa una ruta al directorio con el archivo python.exe
.
-
rueda
The wheel package provides compiled Kivy, but with removed
cython
source components, which means the core code can’t be recompiled using this way. Python code, however, is editable.
La versión estable de Kivy está disponible en pypi.
python -m pip install kivy
The latest version from the official repository is available through nightly-built wheels available on google drive. Visit the link in [docs](https://kivy.org/docs/installation/installation-windows.html#nightly-wheel-installation) matching your python version. After a proper wheel is downloaded, rename it to match the formatting of this example and run the command.
python -m pip install C:\Kivy-1.9.1.dev-cp27-none-win_amd64.whl
- Fuente
Se necesitan más dependencias necesarias para instalar Kivy desde el origen que usar las ruedas, pero la instalación es más flexible.
Cree un nuevo archivo en <python>\Lib\distutils\distutils.cfg
con estas líneas para asegurarse de que se utilizará un compilador adecuado para el código fuente.
[build]
compiler = mingw32
Entonces se necesita el compilador. Utilice alguno que ya tenga instalado o descargue mingwpy
. Los archivos importantes como gcc.exe
se ubicarán en <python>\Scripts
.
python -m pip install -i https://pypi.anaconda.org/carlkl/simple mingwpy
No olvide establecer variables de entorno para que Kivy sepa qué proveedores debe usar.
set USE_SDL2=1
set USE_GSTREAMER=1
Ahora instale las dependencias adicionales requeridas para la compilación.
python -m pip install cython kivy.deps.glew_dev kivy.deps.sdl2_dev
python -m pip install kivy.deps.gstreamer_dev --extra-index-url https://kivy.org/downloads/packages/simple/
Verifique la sección Rutas
para asegurarse de que todo esté configurado correctamente e instale Kivy. Elija una de estas opciones:
python -m pip install C:\master.zip
python -m pip install https://github.com/kivy/kivy/archive/master.zip
Caminos
Kivy necesita acceso a los binarios desde algunas dependencias. Esto significa que las carpetas correctas tienen que estar en la variable PATH
del entorno.
set PATH=<python>\Tools;<python>\Scripts;<python>\share\sdl2\bin;%PATH%
De esta forma, Python IDLE IDE se puede incluir en la ruta con <python>\Lib\idlelib;
. Luego escriba idle
en la consola y IDLE estará listo para usar Kivy.
Simplificalo
Para evitar la configuración repetitiva de las variables de entorno, configure cada ruta necesaria [de esta manera] (http://superuser.com/questions/737542) o cree un archivo por lotes (.bat
) con estas líneas colocadas 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 <nombre de archivo>.py
instalación en Ubuntu
Para instalar kivy en ubuntu con el ejemplo de kivy, abra la terminal y ejecute el siguiente comando
Primero agrega ppa
sudo add-apt-repository ppa:kivy-team/kivy
Para instalar kivy
sudo apt-get install python-kivy
Para instalar ejemplos de kivy
sudo apt-get install python-kivy-example
Hola mundo desesperado.
El siguiente código ilustra cómo crear la aplicación ‘hola mundo’ en kivy. Para ejecutar esta aplicación en iOS y Android, guárdela como main.py y use buildozer.
from kivy.app import App
from kivy.uix.label import Label
from kivy.lang import Builder
Builder.load_string('''
<SimpleLabel>:
text: 'Hello World'
''')
class SimpleLabel(Label):
pass
class SampleApp(App):
def build(self):
return SimpleLabel()
if __name__ == "__main__":
SampleApp().run()
Vista de reciclaje
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
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]}
]
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()
Diferentes formas de ejecutar una aplicación simple e interactuar con widgets
La mayoría de las aplicaciones kivy comienzan con esta estructura:
from kivy.app import App
class TutorialApp(App):
def build(self):
return
TutorialApp().run()
Hay varias formas de ir desde aquí:
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.
Ejemplo 1: devolución de un solo widget (aplicación Hello World simple)
from kivy.app import App
from kivy.uix.button import Button
class TutorialApp(App):
def build(self):
return Button(text="Hello World!")
TutorialApp().run()
Ejemplo 2: devolver varios widgets + el botón imprime el texto de la etiqueta
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
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: usar una clase (widget único) + el botón imprime “Mi botón”
from kivy.app import App
from kivy.uix.button import Button
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 cómo usar una clase **
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
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()
Con lenguaje .kv
Ejemplo 5: lo mismo pero mostrando cómo usar el lenguaje kv dentro de python
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
# BoxLayout: it's in the python part, so you need to import it
from kivy.lang import Builder
Builder.load_string("""
<MyLayout>
orientation:"vertical"
Label: # it's in the kv part, so no need to import it
id:mylabel
text:"My App"
Button:
text: "Click me!"
on_press: print(mylabel.text)
""")
class MyLayout(BoxLayout):
pass
class TutorialApp(App):
def build(self):
return MyLayout()
TutorialApp().run()
**Ejemplo 6: lo mismo con la parte kv
en un archivo Tutorial.kv
**
En .py:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
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:
<MyLayout> # no need to import stuff in kv!
orientation:"vertical"
Label:
id:mylabel
text:"My App"
Button:
text: "Click me!"
on_press: print(mylabel.text)
**Ejemplo 7: enlace a un archivo kv específico + una definición en python que recibe la etiqueta.texto **
En .py:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
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:
Ejemplo 8: el botón imprime el texto de la etiqueta (con una definición en python usando ids
(los “ID”))
Darse cuenta de:
self_xx
del ejemplo 7 se reemplaza porself
En .py:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
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:
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:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
class MyLayout(BoxLayout):
objectProperty_mylabel= ObjectProperty(None)
def printMe(self):
print(self.objectProperty_mylabel.text)
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()