SlideShare uma empresa Scribd logo
1 de 15
Baixar para ler offline
KIVY
NUI Applications with Python
Python Meetup Innsbruck | 25. April 2017
Robert Niederreiter
CROSS PLATFORM
kivy
ARCHITECTURE
Widget Kv Language
Cache Clock Gesture Event Loop Properties
Core Providers
Window
Text
Image
Video
Audio
Graphics
Vertex Buffer
Frame Buffer
Texture
Shader
Instructions
Inputs
Motion Event
Post Processing
(double tab,
Dejitter, …)
Pygame PIL Gstreamer
FFMpeg SDL Cairo
GLES API GLEW
MouseTUIO WM_Touch
Mac TouchMTDev HIDInput
App brought to foreground
After process is killed (Android/iOS)
Kivy bootstrap for Android/iOS
Python start, run()
build()
on_start()
Apps functionson_resume()
Extenal App/OS or internal
function pauses App
on_pause()
Save your work here.
Resume is not guaranteed.
on_stop()
Kivy window destroyed
Python stop
on_pause()
Resume?
return True
return False
NoYes
LIFECYCLE
EVENT LOOP
Clock Events Loop
Filesystem
Network
Process
Other
Motion Events
Post Processing
(double tab, swipe, ...)
Input Processing
Event
Dispatcher
Dispatch Input Events
Custom Events
Property Events
Window Events
GUI
Touch
Mouse
Keyboard
Joystick
Other
Input Kivy Main Thread
Non GUI
Operations
(may run in
dedicated thread)
Main
Loop
EventDispatcher
App
Widget
Widgets are self-contained
and organized as tree
Animation
Clock
MotionEvent
Layout
Controls size and
position of it's children
FloatLayout
BoxLayout
GridLayout
ButtonBehavior
CoverBehavior
DragBehavior
behaviors
...
Button
Switch
Slider
Popup
...
uix
graphics
Widget representation is done using canvas, graphics
instructions are applied to it
ContextInstruction VertexInstruction
Color
Rotate
Scale
...
Triangle
Rectangle
Ellipse
...
Kv Language
The KV language (sometimes called kvlang, or kivy language),
allows you to create your widget tree in a declarative way
and to bind widget properties to each other or to callbacks in a
natural manner.
...
OBJECTS
Mixin Classes for Widgets
APPLICATION
import kivy
# replace with your current kivy version
kivy.require('1.9.1')
from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):
# MyApp inherits from App object
def build(self):
# build returns the root widget
return Label(text='Hello world')
if __name__ == '__main__':
MyApp().run()
REPETITIVE EVENTS
from kivy.clock import Clock
def my_callback(dt):
# ``dt`` is delta time
print('My callback is called'.format(dt))
# call ``my_callback`` X times per second
event = Clock.schedule_interval(my_callback, 1 / 30.)
# unscedule can be done by either using
event.cancel()
# or
Clock.unschedule(event)
def my_callback(dt):
# if repetitive callback returns False, it gets unscheduled as well
if some_condition:
return False
# regular processing
Clock.schedule_interval(my_callback, 1 / 30.)
ONE-TIME EVENTS
from kivy.clock import Clock
def my_callback(dt):
print('My callback is called'.format(dt))
# call ``my_callback`` once in one second
Clock.schedule_once(my_callback, 1)
The second argument is the amount of time to wait before calling the function,
in seconds. However, you can achieve some other results with special values
for the second argument:
● If X is greater than 0, the callback will be called in X seconds
● If X is 0, the callback will be called after the next frame
● If X is -1, the callback will be called before the next frame
INPUT AND PROPERTY EVENTS
from kivy.uix.widget import Widget
from kivy.properties import ListProperty
class CustomBtn(Widget):
# it's possible to bind to kivy property changes
pressed = ListProperty([0, 0])
def on_touch_down(self, touch):
# event handler for regular touch events
if self.collide_point(*touch.pos):
# setting pressed property triggers property event
self.pressed = touch.pos
# return True to indicate event consumed
return True
# delegate touch event to super class
return super(CustomBtn, self).on_touch_down(touch)
def on_pressed(self, instance, pos):
# event handler triggered if ``pressed`` property changed
print('pressed at {pos}'.format(pos=pos))
CUSTOM EVENTS
from kivy.event import EventDispatcher
class MyEventDispatcher(EventDispatcher):
def __init__(self, **kw):
# register custom event
self.register_event_type('on_test')
super(MyEventDispatcher, self).__init__(**kw)
def do_something(self, value):
# when do_something is called, the 'on_test' event will be
# dispatched with the value
self.dispatch('on_test', value)
def on_test(self, *args):
# default event handler
print('I am dispatched'.format(args))
def my_callback(value, *args):
print('Hello, I got an event!'.format(args))
ev = MyEventDispatcher() # instanciate ``MyEventDispatcher``
ev.bind(on_test=my_callback) # bind ``my_callback`` to ``on_test``
ev.do_something('test') # ``do_something`` dispatches ``on_test``
WIDGET TREE
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
# create widget and add children
layout = BoxLayout(padding=10)
button = Button(text='My first button')
layout.add_widget(button)
# remove child from widget
layout.remove_widget(button)
# clear children
layout.clear_widgets()
# traversing the tree, iterate widget children
for child in layout.children:
print(child)
# traversing the tree, access parent widget
child = layout.children[0]
Layout = child.parent
# setting a z-index for a child widget
layout.add_widget(widget, index)
KV LANGUAGE
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
Builder.load_string('''
<CustomLayout>
Button:
text: 'Hello World!!'
size_hint: .5, .5
pos_hint: {'center_x': .5, 'center_y': .5}
''')
class CustomLayout(FloatLayout):
pass
As your application grow more complex, it’s common that the construction of widget
trees and explicit declaration of bindings, becomes verbose and hard to maintain.
The KV Language is a attempt to overcome these short-comings.
In the example above KV code is defined inside python module as docstring passed
to Builder.load_string. KV code can also be contained in a separate
file which can be loaded by using Builder.load_file('path/to/file.kv')
GRAPHICS
class MyWidget(Widget):
def __init__(self, **kw):
super(MyWidget, self).__init__(**kw)
with self.canvas:
# add your instruction for main canvas here
Color(1, 0, .4, mode='rgb')
Line(points=(x1, y1, x2, y2, x3, y3))
with self.canvas.before:
# you can use this to add instructions rendered before
with self.canvas.after:
# you can use this to add instructions rendered after
MyWidget:
canvas:
Color:
rgba: 1, .3, .8, .5
Line:
points: zip(self.data.x, self.data.y)
Graphics instructions in Python
Graphics instructions in KV language
Thank You!
References:
https://kivy.org/docs/guide/basic.html
Credits:
Photos by:
https://www.flickr.com/photos/photos_by_chrystal
https://www.flickr.com/photos/steffireichert
https://creativecommons.org/licenses/by-nc-nd/2.0

Mais conteúdo relacionado

Mais procurados

Android booting sequece and setup and debugging
Android booting sequece and setup and debuggingAndroid booting sequece and setup and debugging
Android booting sequece and setup and debugging
Utkarsh Mankad
 
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
elliando dias
 
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
ScyllaDB
 

Mais procurados (20)

Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021
 
Oracle E-Business Suite on Kubernetes Cluster
Oracle E-Business Suite on Kubernetes ClusterOracle E-Business Suite on Kubernetes Cluster
Oracle E-Business Suite on Kubernetes Cluster
 
OpenStackを使用したGPU仮想化IaaS環境 事例紹介
OpenStackを使用したGPU仮想化IaaS環境 事例紹介OpenStackを使用したGPU仮想化IaaS環境 事例紹介
OpenStackを使用したGPU仮想化IaaS環境 事例紹介
 
Efi booting
Efi bootingEfi booting
Efi booting
 
BeagleBone Black Booting Process
BeagleBone Black Booting ProcessBeagleBone Black Booting Process
BeagleBone Black Booting Process
 
4章 Linuxカーネル - 割り込み・例外 4
 4章 Linuxカーネル - 割り込み・例外 4 4章 Linuxカーネル - 割り込み・例外 4
4章 Linuxカーネル - 割り込み・例外 4
 
DockerCon参加報告 (`docker build`が30倍以上速くなる話など)
DockerCon参加報告 (`docker build`が30倍以上速くなる話など)DockerCon参加報告 (`docker build`が30倍以上速くなる話など)
DockerCon参加報告 (`docker build`が30倍以上速くなる話など)
 
Performance Comparison of Mutex, RWLock and Atomic types in Rust
Performance Comparison of Mutex, RWLock and  Atomic types in RustPerformance Comparison of Mutex, RWLock and  Atomic types in Rust
Performance Comparison of Mutex, RWLock and Atomic types in Rust
 
Ixgbe internals
Ixgbe internalsIxgbe internals
Ixgbe internals
 
Android booting sequece and setup and debugging
Android booting sequece and setup and debuggingAndroid booting sequece and setup and debugging
Android booting sequece and setup and debugging
 
IBTA Releases Updated Specification for RoCEv2
IBTA Releases Updated Specification for RoCEv2IBTA Releases Updated Specification for RoCEv2
IBTA Releases Updated Specification for RoCEv2
 
Qemu device prototyping
Qemu device prototypingQemu device prototyping
Qemu device prototyping
 
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
Distributed Caching Using the JCACHE API and ehcache, Including a Case Study ...
 
ALSS14: Xen Project Automotive Hypervisor (Demo)
ALSS14: Xen Project Automotive Hypervisor (Demo)ALSS14: Xen Project Automotive Hypervisor (Demo)
ALSS14: Xen Project Automotive Hypervisor (Demo)
 
BuildKitによる高速でセキュアなイメージビルド (LT)
BuildKitによる高速でセキュアなイメージビルド (LT)BuildKitによる高速でセキュアなイメージビルド (LT)
BuildKitによる高速でセキュアなイメージビルド (LT)
 
Linux Device Tree
Linux Device TreeLinux Device Tree
Linux Device Tree
 
QEMU - Binary Translation
QEMU - Binary Translation QEMU - Binary Translation
QEMU - Binary Translation
 
Basic Linux Internals
Basic Linux InternalsBasic Linux Internals
Basic Linux Internals
 
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
 
50 Shades of Fuzzing by Peter Hlavaty & Marco Grassi
50 Shades of Fuzzing by Peter Hlavaty & Marco Grassi50 Shades of Fuzzing by Peter Hlavaty & Marco Grassi
50 Shades of Fuzzing by Peter Hlavaty & Marco Grassi
 

Semelhante a Kivy Talk Python Meetup Innsbruck 2017.04.25

2011 py con
2011 py con2011 py con
2011 py con
Eing Ong
 

Semelhante a Kivy Talk Python Meetup Innsbruck 2017.04.25 (20)

GWT MVP Case Study
GWT MVP Case StudyGWT MVP Case Study
GWT MVP Case Study
 
The Ring programming language version 1.5.1 book - Part 175 of 180
The Ring programming language version 1.5.1 book - Part 175 of 180 The Ring programming language version 1.5.1 book - Part 175 of 180
The Ring programming language version 1.5.1 book - Part 175 of 180
 
2011 py con
2011 py con2011 py con
2011 py con
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
The Ring programming language version 1.9 book - Part 99 of 210
The Ring programming language version 1.9 book - Part 99 of 210The Ring programming language version 1.9 book - Part 99 of 210
The Ring programming language version 1.9 book - Part 99 of 210
 
09events
09events09events
09events
 
Day 5
Day 5Day 5
Day 5
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
 
Titanium Appcelerator - Beginners
Titanium Appcelerator - BeginnersTitanium Appcelerator - Beginners
Titanium Appcelerator - Beginners
 
CQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony applicationCQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony application
 
How to dispatch redux action with timeout
How to dispatch redux action with timeoutHow to dispatch redux action with timeout
How to dispatch redux action with timeout
 
Gevent be or not to be
Gevent be or not to beGevent be or not to be
Gevent be or not to be
 
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in Odoo
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Writing videogames with titanium appcelerator
Writing videogames with titanium appceleratorWriting videogames with titanium appcelerator
Writing videogames with titanium appcelerator
 
NestJS
NestJSNestJS
NestJS
 
MOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentMOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app development
 
mobl
moblmobl
mobl
 

Último

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Último (20)

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 

Kivy Talk Python Meetup Innsbruck 2017.04.25

  • 1. KIVY NUI Applications with Python Python Meetup Innsbruck | 25. April 2017 Robert Niederreiter
  • 3. ARCHITECTURE Widget Kv Language Cache Clock Gesture Event Loop Properties Core Providers Window Text Image Video Audio Graphics Vertex Buffer Frame Buffer Texture Shader Instructions Inputs Motion Event Post Processing (double tab, Dejitter, …) Pygame PIL Gstreamer FFMpeg SDL Cairo GLES API GLEW MouseTUIO WM_Touch Mac TouchMTDev HIDInput
  • 4. App brought to foreground After process is killed (Android/iOS) Kivy bootstrap for Android/iOS Python start, run() build() on_start() Apps functionson_resume() Extenal App/OS or internal function pauses App on_pause() Save your work here. Resume is not guaranteed. on_stop() Kivy window destroyed Python stop on_pause() Resume? return True return False NoYes LIFECYCLE
  • 5. EVENT LOOP Clock Events Loop Filesystem Network Process Other Motion Events Post Processing (double tab, swipe, ...) Input Processing Event Dispatcher Dispatch Input Events Custom Events Property Events Window Events GUI Touch Mouse Keyboard Joystick Other Input Kivy Main Thread Non GUI Operations (may run in dedicated thread) Main Loop
  • 6. EventDispatcher App Widget Widgets are self-contained and organized as tree Animation Clock MotionEvent Layout Controls size and position of it's children FloatLayout BoxLayout GridLayout ButtonBehavior CoverBehavior DragBehavior behaviors ... Button Switch Slider Popup ... uix graphics Widget representation is done using canvas, graphics instructions are applied to it ContextInstruction VertexInstruction Color Rotate Scale ... Triangle Rectangle Ellipse ... Kv Language The KV language (sometimes called kvlang, or kivy language), allows you to create your widget tree in a declarative way and to bind widget properties to each other or to callbacks in a natural manner. ... OBJECTS Mixin Classes for Widgets
  • 7. APPLICATION import kivy # replace with your current kivy version kivy.require('1.9.1') from kivy.app import App from kivy.uix.label import Label class MyApp(App): # MyApp inherits from App object def build(self): # build returns the root widget return Label(text='Hello world') if __name__ == '__main__': MyApp().run()
  • 8. REPETITIVE EVENTS from kivy.clock import Clock def my_callback(dt): # ``dt`` is delta time print('My callback is called'.format(dt)) # call ``my_callback`` X times per second event = Clock.schedule_interval(my_callback, 1 / 30.) # unscedule can be done by either using event.cancel() # or Clock.unschedule(event) def my_callback(dt): # if repetitive callback returns False, it gets unscheduled as well if some_condition: return False # regular processing Clock.schedule_interval(my_callback, 1 / 30.)
  • 9. ONE-TIME EVENTS from kivy.clock import Clock def my_callback(dt): print('My callback is called'.format(dt)) # call ``my_callback`` once in one second Clock.schedule_once(my_callback, 1) The second argument is the amount of time to wait before calling the function, in seconds. However, you can achieve some other results with special values for the second argument: ● If X is greater than 0, the callback will be called in X seconds ● If X is 0, the callback will be called after the next frame ● If X is -1, the callback will be called before the next frame
  • 10. INPUT AND PROPERTY EVENTS from kivy.uix.widget import Widget from kivy.properties import ListProperty class CustomBtn(Widget): # it's possible to bind to kivy property changes pressed = ListProperty([0, 0]) def on_touch_down(self, touch): # event handler for regular touch events if self.collide_point(*touch.pos): # setting pressed property triggers property event self.pressed = touch.pos # return True to indicate event consumed return True # delegate touch event to super class return super(CustomBtn, self).on_touch_down(touch) def on_pressed(self, instance, pos): # event handler triggered if ``pressed`` property changed print('pressed at {pos}'.format(pos=pos))
  • 11. CUSTOM EVENTS from kivy.event import EventDispatcher class MyEventDispatcher(EventDispatcher): def __init__(self, **kw): # register custom event self.register_event_type('on_test') super(MyEventDispatcher, self).__init__(**kw) def do_something(self, value): # when do_something is called, the 'on_test' event will be # dispatched with the value self.dispatch('on_test', value) def on_test(self, *args): # default event handler print('I am dispatched'.format(args)) def my_callback(value, *args): print('Hello, I got an event!'.format(args)) ev = MyEventDispatcher() # instanciate ``MyEventDispatcher`` ev.bind(on_test=my_callback) # bind ``my_callback`` to ``on_test`` ev.do_something('test') # ``do_something`` dispatches ``on_test``
  • 12. WIDGET TREE from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button # create widget and add children layout = BoxLayout(padding=10) button = Button(text='My first button') layout.add_widget(button) # remove child from widget layout.remove_widget(button) # clear children layout.clear_widgets() # traversing the tree, iterate widget children for child in layout.children: print(child) # traversing the tree, access parent widget child = layout.children[0] Layout = child.parent # setting a z-index for a child widget layout.add_widget(widget, index)
  • 13. KV LANGUAGE from kivy.uix.floatlayout import FloatLayout from kivy.lang import Builder Builder.load_string(''' <CustomLayout> Button: text: 'Hello World!!' size_hint: .5, .5 pos_hint: {'center_x': .5, 'center_y': .5} ''') class CustomLayout(FloatLayout): pass As your application grow more complex, it’s common that the construction of widget trees and explicit declaration of bindings, becomes verbose and hard to maintain. The KV Language is a attempt to overcome these short-comings. In the example above KV code is defined inside python module as docstring passed to Builder.load_string. KV code can also be contained in a separate file which can be loaded by using Builder.load_file('path/to/file.kv')
  • 14. GRAPHICS class MyWidget(Widget): def __init__(self, **kw): super(MyWidget, self).__init__(**kw) with self.canvas: # add your instruction for main canvas here Color(1, 0, .4, mode='rgb') Line(points=(x1, y1, x2, y2, x3, y3)) with self.canvas.before: # you can use this to add instructions rendered before with self.canvas.after: # you can use this to add instructions rendered after MyWidget: canvas: Color: rgba: 1, .3, .8, .5 Line: points: zip(self.data.x, self.data.y) Graphics instructions in Python Graphics instructions in KV language