Post on 01-Feb-2020
transcript
Kivy DocumentationRelease 1.0.4-dev
www.kivy.org
CONTENTS
I User’s Guide 3
1 Philosophy 51.1 Why bother? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Programming Guide 72.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.2 Quickstart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.3 Architectural Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.4 Running on mobile platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3 Contributing 173.1 Reporting an issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.2 Code Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.3 Documentation Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4 Frequently Asked Questions 214.1 Why do you use Python? Isn’t it slow? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.2 Does Kivy support Python 3.x? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224.3 How is Kivy related to PyMT? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224.4 Do you accept patches? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224.5 Does the Kivy project participate in Google’s Summer of Code 2011? . . . . . . . . . . . . 22
5 Contact Us 235.1 Issue Tracker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235.2 Mail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235.3 IRC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
II API Reference 25
6 Kivy framework 276.1 Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286.2 Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306.3 Event loop management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326.4 Cache manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326.5 Clock object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346.6 Configuration object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356.7 Event dispatcher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376.8 Factory object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386.9 Gesture recognition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386.10 Kivy language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406.11 Asynchronous data loader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
i
6.12 Logger object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456.13 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456.14 Resources management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486.15 Utils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486.16 Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496.17 Weak Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
7 Core Abstraction 537.1 Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537.2 Camera . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547.3 Clipboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557.4 OpenGL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557.5 Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557.6 Spelling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567.7 SVG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577.8 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587.9 Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597.10 Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
8 Graphics 638.1 The basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638.2 Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638.3 Graphics compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638.4 Context instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648.5 Framebuffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668.6 Canvas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678.7 Texture management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708.8 Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 738.9 Vertex Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
9 Input management 779.1 Input Postprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779.2 Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799.3 Motion Event Factory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829.4 Motion Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839.5 Motion Event Provider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 879.6 Motion Event Shape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
10 Modules 89
11 UIX 9111.1 Anchor layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9111.2 Box Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9111.3 Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9211.4 Camera . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9311.5 Float Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9411.6 Grid layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9511.7 Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9611.8 Label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9711.9 Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9911.10 Scatter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10011.11 Slider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10411.12 Text Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10511.13 Toggle button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11011.14 Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11011.15 Widget class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
ii
III Indices and tables 117
Python Module Index 119
Index 121
iii
iv
Welcome to Kivy’s documentation. Kivy is an open source software library for rapid development ofapplications equipped with novel user interfaces, such as multi-touch apps.
You are probably wondering why you’d be interested in using Kivy. There is a document outlining ourPhilosophy that we encourage you to read.
We recommend that you get started with Installation and then head over to the Quickstart document.Besides the quickstart, there is also a more detailed Architectural Overview.
If you want to contribute to Kivy, make sure to read Contributing. If your concern isn’t addressed in thedocumentation, feel free to Contact Us.
1
2
Part I
USER’S GUIDE
This part of the documentation explains the basic ideas behind Kivy’s design and why you’d want to useit. It goes on with a discussion of the architecture and shows you how to create stunning applicationsin short time using the framework.
3
4
CHAPTER
ONE
PHILOSOPHY
In case you are wondering what Kivy is all about and sets it apart from different solutions, this docu-ment is for you.
1.1 Why bother?
Why would you want to use Kivy? After all, there is many a great toolkit (or framework, or platform)available out there – for free. Qt and Flash, to just name two good choices for application development,and many of these numerous solutions already support Multi-Touch. So what is it that makes Kivyspecial and worth using?
1.1.1 Fresh
Kivy is made for today and tomorrow. Novel input methods such as Multi-Touch become increasinglyimportant. We created Kivy from scratch, specifically for this kind of interaction. That means we wereable to rethink many things in terms of human computer interaction where older (not saying ‘outdated’;rather ‘well-established’) toolkits carry their legacy, which is often a burden. We’re not trying to forcethis new approach to using a computer into the corset of existing models (say single-pointer mouseinteraction). We want to let it flourish and let you explore the possibilities. This is what really sets Kivyapart.
1.1.2 Fast
Kivy is fast. This applies to both: application development and application execution speeds. We have opti-mized Kivy in many ways. We implement time-critical functionality on the C level to leverage the powerof existing compilers. More importantly, we also use intelligent algorithms to minimize costly operations.Most importantly, we use the GPU wherever it makes sense in our context. The computational powerof today’s graphics cards surpasses that of today’s CPUs by far for some tasks and algorithms, espe-cially drawing. That’s why we try to let the GPU do as much of the work as possible, thus increasingperformance considerably.
1.1.3 Flexible
Kivy is flexible. This means it can be run on a variety of different devices, including Android poweredsmartphones and tablets. We support all major operating systems (Windows, Linux, OS X). Being flexiblealso means that Kivy’s fast-paced development allows it to adapt to new technologies quickly. More thanonce have we added support for new external devices and software protocols; sometimes even beforethey were released. Lastly, Kivy is also flexible in that it is possible to use it in combination with a greatnumber of different third-party solutions. For example, on Windows we support WM_TOUCH, which
5
means that any device that has Windows 7 Pen & Touch drivers will just work with Kivy. On OS X youcan use Apple’s Multi-Touch capable devices, such as trackpads and mice. On Linux, you can use HIDkernel input events. In addition to that, we support TUIO and a number of other input sources.
1.1.4 Focused
Kivy is focused. You can write a simple application with a few lines of code. Kivy programs are createdby using the Python programming language, which is incredibly versatile, powerful yet easy to use. Inaddition, we created our own description language, the Kivy Language, for creating sophisticated userinterfaces. This language allows you to set up, connect and arrange your application elements quickly.We feel that allowing you to focus on the essence of your application is more important than forcingyou to fiddle with compiler settings. We took that burden off your shoulders.
1.1.5 Funded
Kivy is actively developed by professionals in their field. Kivy is a community-influenced, profession-ally developed and commercially backed solution. Some of our core developers develop Kivy for aliving. Kivy is here to stay. It’s not a small, vanishing student project.
1.1.6 Free
Kivy is free to use. You don’t have to pay for it. You don’t even have to pay for it if you’re makingmoney out of selling an application that uses Kivy.
6
CHAPTER
TWO
PROGRAMMING GUIDE
2.1 Installation
We try not to reinvent the wheel but bring something innovative to the market. As a consequence, we’refocused on our own code and use already existing, high-qualitative third-party libraries where possi-ble. For the rich set of features that Kivy offers, several other libraries are required. If you do not usea specific feature (e.g. video playback) you don’t need the corresponding dependency, however. Thatsaid, there are one dependency that Kivy does require: Cython. In addition, you need a Python 2.x (not3.x) interpreter. If you want to enable features like windowing (i.e., open a Window), audio/video play-back or spelling correction, you must install other dependencies. For these, we recommend Pygame,Gst-Python and Enchant, respectively.
Other optional libraries (mutually interchangable) are:
• OpenCV 2.0: Camera input.
• PIL: Image and text display.
• PyCairo: Text display.
• PyEnchant: Spelling correction.
• Pygame : Window creation, image and text display, audio playback.
• PyGST: Audio/video playback and camera input.
2.1.1 Stable version
The latest stable version can be found on the Kivy’s website at http://kivy.org/#downloads Select theinstallations instructions for your platform:
Installation on Windows
The windows stable version is what we call a portable package. You don’t have to install anything in“system” wide. Just unzip & run:
1. Download the latest version from http://kivy.org/#downloads
2. Unzip the package
3. Then, in the unzipped package, you have a script called kivy.bat, use it for launching any kivyapplication
7
Start any Kivy’s application
If you want to double-click and make it just “work”, you need to use the kivy.bat included in the packagefor starting Kivy application. To make it work, do
1. Right click on the python file of the application
2. Open With
3. Select the default software
4. Browse your files to select the kivy.bat
5. Select “Always open the file with...” if you want
6. Ok !
Next time, your python file will be executed with the Kivy’s python !
Start from commandline
If you want just to use or develop with latest stable kivy, we offer you an alternative way with a console.You need a minimalist GNU system installed on your system. Use msysGit.
When you install the msysGit, you must select theses options:
• Don’t replace windows shell
• Checkout at-is, commit at-is (no clrf replacement !)
You’ll have an icon “Git bash” on your desktop, this is the console we want:
1. Start “Git bash”
2. cd “directory of portable kivy”
3. source kivyenv.sh “full directory of portable kivy” (don’t use .)
You are now ready to launch python/kivy in commande line ! Just do:
python <filename.py>
Also, all other scripts and binary are available such as:
• cython
• gcc / make...
• easy_install
• gst-inspect-0.10
Content of the package
The latest windows package contain:
• Latest kivy stable version
• Python 2.7.1
• Glew 1.5.7
• Pygame 1.9.2
• Cython 0.14
• MingW
8
• Gstreamer
• Setuptools
Installation on MacOSX
Note: This method has only been tested on Mac OSX 10.6 Snow Leopard 64-bit. For versions prior to10.6 or 10.6 32-bit, you have to install the components yourself. We suggest using homebrew to do that.
For Mac OS X 10.6 and later, we provide a Kivy.app with all dependencies bundled. Download it fromour google code project page. It comes as a .dmg file that contains:
• Kivy.app
• Readme.txt
• An Examples folder
• A script to install a kivy command for shell usage
To install Kivy, you must:
1. Download the latest version from http://kivy.org/#downloads
2. Double-click to open it
3. Drag the Kivy.app into your Applications folder
4. Make sure to read the Readme.txt
Start any Kivy Application
You can run any Kivy application by simply dragging the application’s main file onto the Kivy.app icon.Just try with any python file in the examples folder.
Start from Command Line
If you want to use Kivy from the command line, double-click the Make Symlinks script after youdragged the Kivy.app into the Applications folder. To test if it worked:
1. Open Terminal.app and run kivy. You should get a Python prompt.
2. In there, enter import kivy. If it just goes to the next line without errors, it worked.
3. Running any Kivy application from the command line is now simply a matter of executing acommand like the following: kivy yourapplication.py
Installation on Ubuntu
Ubuntu 10.10 (Maverick)
$ sudo apt-get install python-setuptools python-pygame python-opengl \python-gst0.10 python-enchant gstreamer0.10-plugins-good cython python-dev \build-essential libgl1-mesa-dev libgles2-mesa-dev
$ easy_install kivy
If you already installed kivy before, you can upgrade it with:
9
$ easy_install -U kivy
Start from Command Line
You can know run any example from the examples directory of kivy:
$ cd <path to kivy directory>/examples/demo$ python touchtracer.py
Installation on Android
Note: The android version is not fully supported yet. Check Android platform for more informationabout the current status.
You remind you that Kivy is a framework. Installing Kivy itself on your phone will do absolutly noth-ing. Kivy is not an application.
BUT, despite this agreement, we are releasing a “launcher”, that permit you to push your kivy appli-cation onto your phone, and execute them through a simple interface. We’ll provide instruction forpackaging your kivy application in the future.
To install Kivy launcher, you can:
1. Go on the Kivy Launcher on the Android market
2. Click on Install
3. Select your phone.. and you’re done !
Now, you can push your Kivy’s applications in the kivy directory on the sdcard. Check the Androidplatform for learning specials tricks for android platform.
Installation of examples
Warning: Theses examples are not final, just tests for Kivy environment.
1. Download the KivyTest for Android
2. Unzip the content into your sdcard of your phone, in the kivy directory:
/sdcard/kivy
3. Run the launcher and select Kivytest
2.1.2 Development Version
The development version is for developers and testers. Note that when running a development version,you’re running potentially broken code at your own risk. To use the development version, you will firstneed to install the dependencies. Afterwards you have to set up Kivy on your computer in a way thatallows for easy development. For that, please see our Contributing document.
Installing Dependencies
To install Kivy’s dependencies, follow the guide below for your platform.
10
Ubuntu
For Ubuntu, simply enter the following command that will install all necessary packages:
$ sudo apt-get install python-setuptools python-pygame python-opengl \python-gst0.10 python-enchant gstreamer0.10-plugins-good cython python-dev \build-essential libgl1-mesa-dev libgles2-mesa-dev
Installing Kivy for Development
Now that you’ve installed all the required dependencies, it’s time to download and compile a develop-ment version of Kivy:
$ # Download Kivy from GitHub$ git clone git://github.com/tito/kivy.git$ cd kivy
$ # Compile:$ python setup.py build_ext --inplace -f
If you have the make command available, you can also use the following shortcut to compile (does thesame as the last two commands):
$ make build
If you want to modify the Kivy codebase itself, set up the PYTHONPATH environment variable to pointat your clone. This way you don’t have to install (setup.py install) after every tiny modification.Python will instead import Kivy from your clone.
Or, if you don’t want to make any changes to Kivy itself, you can also run (as admin, e.g. with sudo):
$ python setup.py install
If you want to contribute code (patches, new features) to the Kivy codebase, please read Contributing.
2.2 Quickstart
This page explains how to create a simple Kivy “Hello world” program. This assumes you already haveKivy installed. If you do not, head over to the Installation section. We also assume basic Python 2.xknowledge.
2.2.1 Create an application
The base code for creating an application looks like this:
import kivykivy.require(’1.0.0’)
from kivy.app import Appfrom kivy.uix.button import Button
class MyApp(App):def build(self):
return Button(text=’Hello World’)
MyApp().run()
11
Save it as main.py.
Now, to run your application, depending of your platform, you can :
Linux Follow the instructions for running Kivy application on Linux:
$ python main.py
Windows Follow the instructions for running Kivy application on Windows:
$ python main.py# orC:\appdir>kivy.bat main.py
MacOSX Follow the instructions for running Kivy application on MacOSX:
$ kivy main.py
Android You application need some complementary files to be able to run on Android. SeeAndroid platform for more informations.
A window should open, showing a sole button (with the label ‘Hello World’) that covers the entirewindow’s area. That’s all there is to it.
So what does that code do?
1. First, we import Kivy, and check if the current installed version will be enough for our application.If not, an exception will be automatically fired, and prevent your application to crash in runtime.You can read the documentation of kivy.require() function for more information.
2. We import the App class, to be able to subclass it. By subclassing this class, your own class gainsseveral features that we already developed for you to make sure it will be recognized by Kivy.
3. Next, we import the Button class, to be able to create an instance of a button with a custom label.
4. Then, we create our application class, based on the App class. We extend the build() functionto be able to return an instance of Button. This instance will be used as the root of the widgettree (because we returned it).
5. Finally, we call run() on our application instance to launch the Kivy process with our applicationinside.
2.3 Architectural Overview
We would like to take a moment to explain how we designed Kivy from a software engineering point ofview. This is key to understanding how everything works together. If you just look at the code, chancesare you will get a rough idea already, but since this approach certainly is daunting for most users, thissection explains the basic ideas of the implementation in more detail.
Kivy consists of several building blocks that we will explain in the following.
2.3.1 Core Providers and Input Providers
One idea that is key to understanding Kivy’s internals is that of modularity and abstraction. We try toabstract from basic tasks such as opening a window, displaying images and text, playing audio, gettingimages from a camera, spelling correction and so on. We call these core tasks. This makes the API botheasy to use and easy to extend. Most importantly, it allows us to use – what we call – specific providersfor the respective scenario in which your app is being run. For example, on OSX, Linux and Windows,there are different native APIs for the different core tasks. A piece of code that uses one of these specificAPIs to talk to the operating system on one side and to Kivy on the other (acting as an intermediate
12
communication layer) is what we call a core provider. The advantage of using specialized core providersfor each platform is that we can fully leverage the functionality exposed by the operating system and actas efficiently as possible. It also gives users a choice. Furthermore, by using libraries that are shippedwith any one platform, we effectively reduce the size of the Kivy distribution and make packagingeasier. It’s also easier to port Kivy to other platforms. The Android port did greatly benefit from this.
We follow the same concept with input handling. An input provider is a piece of code that adds supportfor a specific input device, such as Apple’s trackpads, TUIO or a mouse emulator. If you need to addsupport for a new input device, you can simply provide a new class that reads your input data fromyour device and transforms them into Kivy basic events.
2.3.2 Graphics
Kivy’s graphics API is our abstraction of OpenGL. On the lowest level, Kivy issues hardware-accelerated drawing commands using OpenGL. Writing OpenGL code however can be a bit confusing,especially to newcomers. That’s why we provide the graphics API that lets you draw things usingsimple metaphors that do not exist as such in OpenGL (e.g. Canvas, Rectangle, etc.).
All of our widgets themselves use this graphics API, which is implemented on the C level for perfor-mance reasons.
Another advantage of the graphics API is its ability to automatically optimize the drawing commandsthat your code issues. This is especially helpful if you’re not an expert at tuning OpenGL. This makesyour drawing code more efficient in many cases.
You can, of course, still use raw OpenGL commands if you prefer that. The version we target is OpenGL2.0 ES (GLES2) on all devices, so if you want to stay cross-platform compatible, we advise you to onlyuse the GLES2 functions.
2.3.3 Core
The code in the core package provides commonly used features, such as:
Clock You can use the clock to schedule timer events. Both one-shot timers and periodictimers are supported
Cache If you need to cache something that you use often, you can use our class for thatinstead of writing your own.
Gesture Detection We ship a simple gesture recognizer that you can use to detect vari-ous kinds of strokes, such as circles or rectangles. You can train it to detect your ownstrokes.
Kivy Language The kivy language is used to easily and efficiently describe user interfaces.
Properties These are not the normal properties that you may know from python. It is ourown properties class that links your widget code with the user interface description.
2.3.4 UIX (Widgets & Layouts)
The UIX module contains commonly used widgets and layouts that you can reuse to quickly create auser interface.
Widgets Widgets are user interface elements that you add to your program to providesome kind of functionality. They may or may not be visible. Examples would be afile browser, buttons, sliders, lists and so on. Widgets receive MotionEvents.
13
Layouts You use layouts to arrange widgets. It is of course possible to calculate your wid-gets’ positions yourself, but often it is more convenient to use one of our ready madelayouts. Examples would be Grid Layouts or Box Layouts. You can also nest layouts.
2.3.5 Modules
If you’ve ever used a modern web browser and customized it with some add-ons then you alreadyknow the basic idea behind our module classes. Modules can be used to inject functionality into Kivyprograms, even if the original author did not include it.
An example would be a module that always shows the FPS of the current application and some graphdepicting the FPS over time.
You can also write your own modules.
2.3.6 Input Events (Touches)
Kivy abstracts from different input types and sources such as touches, mice, TUIO or similar. What all ofthese input types have in common is that you can associate a 2D onscreen-position with any individualinput event. (There are other input devices such as accelerometers where you cannot easily find a 2Dposition for e.g. a tilt of your device. This kind of input is handled separately. In the following wedescribe the former types.)
All of these input types are represented by instances of the Touch() class. (Note that this does not onlyrefer to finger touches, but all the other input types as well. We just called it Touch for the sake ofsimplicity. Think of it of something that touches the user interface or your screen.) A touch instance, orobject, can be in one of three states. When a touch enters one of these states, your program is informedthat the event occurred. The three states a touch can be in are:
Down A touch is down only once, at the very moment where it first appears.
Move A touch can be in this state for a potentially unlimited time. A touch does not haveto be in this state during its lifetime. A ‘Move’ happens whenever the 2D position of atouch changes.
Up A touch goes up at most once, or never. In practice you will almost always receive anup event because nobody is going to hold a finger on the screen for all eternity, but it isnot guaranteed. If you know the input sources your users will be using, you will knowwhether or not you can rely on this state being entered.
2.3.7 Widgets and Event Dispatching
The term widget is often used in GUI programming contexts to describe some part of the program thatthe user interacts with. For Kivy, a widget is an object that receives input events. It does not necessarilyhave to have a visible representation on the screen. All widgets are arranged in a widget tree (which is atree data structure as known from computer science classes): One widget can have any number of childwidgets or none. There is exactly one root widget at the top of the tree that has no parent widget, and allother widgets are directly or indirectly children of this widget (which is why it’s called the root).
When new input data is available, Kivy sends out one event per touch. The root widget of the widgettree first receives the event. Depending on the state of the touch, the on_touch_down, on_touch_moveor on_touch_up event is dispatched (with the touch as the argument) to the root widget, which resultsin the root widget’s corresponding on_touch_down, on_touch_move or on_touch_up event handlerbeing called.
Each widget (this includes the root widget) in the tree can choose to either digest or pass the eventfurther. If an event handler returns True it means that the event has been digested and handled properly.
14
No further processing will happen with that event. Otherwise, the event handler passes the widget onto its own children by calling its superclass’s implementation of the respective event handler. This goesall the way up to the base Widget class, which – in its touch event handlers – does nothing but pass thetouches to its children:
def on_touch_down(self, touch): # This is the same for move/upfor child in reversed(self.children[:]):
if child.dispatch(’on_touch_down’, touch):return True
This really is much easier than it first seems. Let’s take a look at a simple example. If you want toimplement a line drawing program, you will want to know when a touch starts, moves and ends. Youkeep track of the touch’s positions and draw a line through those points:
TODO PAINTER WIDGET
As you can see, this widget does not really care where the touch occurred. Often times you will want torestrict the area on the screen that a widget watches for touches. You can use a widget’s collide_point()method to achieve this. You simply pass it the touches position and it returns True if the touch is withinthe ‘watched area’ or False otherwise. By default, this checks the rectangular region on the screen that’sdescribed by the widget’s pos (for position; x & y) and size (width & height), but you can override thisbehaviour in your own class.
2.4 Running on mobile platform
2.4.1 Android platform
We want to thanks Renpy Tom for beeing able to run pygame on android, with his Pygame Subset forAndroid project.
The changes made from his project are :
• Support of multitouch event
• OpenGL ES 2.0 surface
• Include more Python modules
• Removing main() function and use __main__ hack.
• Various enhancements on the build system for Kivy
Introduction to the Kivy Launcher
The Kivy launcher is an application to run any kivy examples stored on your sdcard from android.Check the Installation on Android.
Your application must be saved into:
/sdcard/kivy/<yourapplication>
Your application directory must contain:
main.py # <-- Your main application fileandroid.txt # <-- Some indication for running your application
The main.py is the same as your original code. If you want to support android, you must change the__main__ line to:
15
if __name__ in (’__main__’, ’__android__’):YourApp().run()
The android.txt can contain:
title=<Application Title>author=<Your Name>orientation=<portrait|landscape>
Status of the project
Missing providers:
• Video
• Camera
• Audio (can use RenPySound)
Missing features:
• Keyboard mapping for main button
• Keyboard support in future TextInput widget
• Ability to hook app on sleep/wakeup
• Ability for an application to have a settings screen
Working devices
• Motorola Droid 1
• Motorola Droid 2
• Samsung Galaxy Tab
• HTC Desire
• HTC Desire Z
• Xperia 10 (custom ROM 2.1 + GLES 2.0 support)
16
CHAPTER
THREE
CONTRIBUTING
There are many ways in which you can contribute to Kivy. Code patches are just one thing amongstothers that you can submit to help the project. We also welcome bug reports, feature requests, documen-tation improvements, advertisement & advocating, testing, graphics contributions and many differentthings. Just talk to us if you want to help, and we will help you help us.
3.1 Reporting an issue
If you found anything wrong, a crash, segfault, missing documentation, invalid spelling, weird exam-ple, please take 2 minutes to report the issue.
1. Move your logging level to debug by editing <user_directory>/.kivy/config.ini:
[kivy]log_level = debug
2. Execute again your code, and copy/paste the complete output to http://paste.pocoo.org/, in-cluding the log from kivy and the python backtrace.
3. Open https://github.com/tito/kivy/issues/
4. Write a title of your issue
5. Explain how we can do to reproduce the issue + paste the link of the output previously sent onpocoo
6. Validate the issue, you’re done !
If you feel good, you can also try to resolve the bug, and contribute by sending us the patch :) Read thenext section about how to do it.
3.2 Code Contributions
Code contributions (patches, new features) are the most obvious way to help with the project’s devel-opment. Since this is so common we ask you to follow our workflow to most efficiently work with us.Adhering to our workflow ensures that your contribution won’t be forgotten or lost. Also, your namewill always be associated with the change you made, which basically means eternal fame in our codehistory (you can opt-out if you don’t want that).
3.2.1 Git & GitHub
We use git as our version control system for our code base. If you have never used git or a similarDVCS (or even any VCS) before, we strongly suggest you take a look at the great documentation that
17
is available for git online. The Git Community Book or the Git Screencasts are both great ways to learngit. Trust us when we say that git is a great tool. It may seem daunting at first, but after a whileyou’ll (hopefully) love it as much as we do. Teaching you git, however, is well beyond the scope of thisdocument.
Also, we use GitHub to host our code. In the following we will assume that you have a (free) GitHubaccount. While this part is optional, it allows for a tight integration between your patches and ourupstream code base. If you don’t want to use GitHub, we assume you know what you do anyway.
3.2.2 Code Workflow
So here is the initial setup to begin with our workflow (you only need to do this once to install Kivy).Basically you follow the installation instructions from Installing Kivy for Development, but you don’tclone our repository, but the fork you create with the following steps:
1. Log in to GitHub
2. Create a fork of the Kivy repository by clicking the fork button.
3. Clone your fork of our repository to your computer. Your fork will have the git remote name‘origin’ and you will be on branch ‘master’.
4. Compile and set up PYTHONPATH or install (see Installing Kivy for Development).
5. Install our pre-commit hook that ensures your code doesn’t violate our styleguide by executing‘make hook’ in your clone. This will run our styleguide check whenever you do a commit, and ifthere are violations in the parts that you changed, your commit will be aborted. Fix & retry.
Now, whenever you want to create a patch, you follow the following steps:
1. See if there is a ticket in our bug tracker for the fix or feature and announce that you’llbe working on it if it doesn’t yet have an assignee.
2. Create a new, appropriately named branch in your local repository for that specificfeature or bugfix. (Keeping a new branch per feature makes sure we can easily pull inyour changes without pulling any other stuff that is not supposed to be pulled.)
3. Modify the code to do what you want (e.g., fix it).
4. Test the code. Try to do this even for small fixes. You never know whether you haveintroduced some weird bug without testing.
5. Do one or more minimal, atomic commits per fix or per feature. Minimal/Atomicmeans keep the commit clean. Don’t commit other stuff that doesn’t logically belong tothis fix or feature. This is NOT about creating one commit per line changed. Use gitadd -p if necessary.
6. Give each commit an appropriate commit message, so that others who are not familiarwith the matter get a good idea of what you changed.
7. Once you are satisfied with your changes, merge with our upstream repository. We canpull your stuff, but since you know best what you changed, you should do the merge.
8. Push to your remote repository on GitHub.
9. Send a Pull Request with a description of what you changed via the button in the GitHubinterface of your repository. (This is why we forked initially. Your repository is linkedagainst ours.)
Note: When you change parts of the code base that require compilation, you will have torecompile in order for your changes to take effect. The make build command will dothat for you (see the Makefile if you want to execute the steps manually). If you need toclean your current directory from compiled files, execute make clean. If you want to
18
get rid of all files that are not under version control, run make distclean (Caution:If your changes are not under version control, this command will delete them!)
Now we will receive your pull request. We will check whether your changes are clean and make sense(if you talked to us before doing all of this we will have told you whether it makes sense or not). If so,we will pull them and you will get instant karma. Congratulations, you’re a hero!
3.3 Documentation Contributions
Documentation contributions generally follow the same workflow as code contributions, just a bit morelax. We don’t ask you to go through all the hassle just to correct a single typo. For more complexcontributions, please consider following the suggested workflow though.
19
20
CHAPTER
FOUR
FREQUENTLY ASKED QUESTIONS
There are a number of questions that repeatedly need to be answered. The following document tries toanswer some of them.
4.1 Why do you use Python? Isn’t it slow?
Let us try to give a thorough answer; please bear with us.
Python is a very agile language that allows you to do many things in (by comparison) short time.For many development scenarios, we strongly prefer writing our application quickly in a high-levellanguage such as Python, testing it, then optionally optimizing it.
But what about speed? If you compare execution speeds of implementations for a certain set of algo-rithms (esp. number crunching) you will find that Python is a lot slower than say, C++. Now you maybe even more convinced that it’s not a good idea in our case to use Python. Drawing sophisticatedgraphics (and we are not talking about your grandmother’s OpenGL here) is computationally quite ex-pensive and given that we often want to do that for rich user experiences, that would be a fair argument.But, in virtually every case your application ends up spending most of the time (by far) executing thesame part of the code. For Kivy for example, these parts are event dispatching and graphics drawing.Now Python allows you to do something to make these parts much faster.
By using Cython, you can compile your code down to the C level, and from there your usual C com-piler optimizes things. This is a pretty pain free process and if you add some hints to your code, theresult becomes even faster. We are talking about a speed up in performance by a factor of anything inbetween 1x and up to more than 1000x (greatly depends on your code). In Kivy, we did this for you andimplemented the portions of our code where efficiency really is critical on the C level.
For graphics drawing, we also leverage today’s GPUs which are, for some tasks such as graphics ras-terization, much more efficent than a CPU. Kivy does as much as is reasonable on the GPU to maximizeperformance. If you use our Canvas API to do the drawing, there is even a compiler that we inventedwhich optimizes your drawing code automatically. If you keep your drawing on the GPU mostly, muchof your program’s execution speed is not determined by the programming language used, but by thegraphics hardware you throw at it.
We believe that these (and other) optimizations that Kivy does for you already make most applicationsfast enough by far. Often you will even want to limit the speed of the application in order not to wasteresources. But even if this is not sufficient, you still have the option of using Cython for your own codeto greatly speed it up.
Trust us when we say that we have given this very careful thought. We have performed many differentbenchmarks and came up with quite some clever optimizations to make your application run smoothly.
21
4.2 Does Kivy support Python 3.x?
No. Not yet. Python 3 is certainly a good thing; However, it broke backwards compatibility (for goodreasons) which means that some considerable portion of available Python projects do not yet work withPython 3. This also applies to some of the projects that Kivy can use as a dependency, which is why wedidn’t make the switch yet. We would also need to switch our own codebase to Python 3. We didn’tdo that yet because it’s not very high on our priority list, but if somebody doesn’t want to wait for usdoing it, please go ahead. Please note, though, that Python 2.x is still the de facto standard.
4.3 How is Kivy related to PyMT?
Our developers are professionals and are pretty savvy in their area of expertise. However, before Kivycame around there was (and still is) a project named PyMT that was led by our core developers. Welearned a great deal from that project during the time that we developed it. In the more than twoyears of research and development we found many interesting ways on how to improve the design ofour framework. We have done numerous benchmarks and as it turns out, to achieve the great speedand flexibility that Kivy has, we had to rewrite quite a big portion of the codebase, making this abackwards-incompatible but future-proof decision. Most notably are the performance increases, whichare just incredible. Kivy starts and operates just so much faster, due to heavy optimizations. We alsohad the opportunity to work with businesses and associations using PyMT. We were able to test ourproduct on a large diversity of setups and made PyMT work on all of these. Writing a system such asKivy or PyMT is one thing. Making it work under all the different conditions is another. We have agood background here, and brought our knowledge to Kivy.
Furthermore, since some of our core developers decided to stop their full-time jobs and to turn to thisproject completely, it was decided that a more professional foundation had to be laid. Kivy is thatfoundation. It is supposed to be a stable and professional product. Technically, Kivy is not reallya successor to PyMT because there is no easy migration path between them. However, the goal isthe same: Producing high-quality applications for novel user interfaces. This is why we encourageeveryone to base new projects on Kivy instead of PyMT. Active development of PyMT has stalled.Maintenance patches are still accepted.
4.4 Do you accept patches?
Yes, we love patches. In order to ensure a smooth integration of your precious changes, however, pleasemake sure to read our contribution guidelines. Obviously we don’t accept every patch. Your patch hasto be coherent with our styleguide and, more importantly, make sense. It does make sense to talk to usbefore you come up with bigger changes, especially new features.
4.5 Does the Kivy project participate in Google’s Summer of Code 2011?
Since Google announced that there will be a GSoC 2011 we have had many potential students askwhether we would participate. The clear answer is: We don’t know, but we hope so. The NUIGroup willapply as an umbrella organization and then hopefully get chosen as one of the mentoring organizations.Given enough slots for NUIGroup, slots will be dedicated to Kivy. That also depends on the overallquality of the student proposals (i.e. if there is only one Kivy student proposal with a bad quality, Kivywill not get a slot). If you want to participate as a student and want to maximize your chances of beingaccepted, start talking to us today and try fixing some smaller (or larger, if you can ;-) problems to getused to our workflow. If we know you can work well with us, that’d be a big plus.
22
CHAPTER
FIVE
CONTACT US
You can contact us in several different ways:
5.1 Issue Tracker
If you found an issue with the code or have a feature request, please see our issue tracker. If there isno issue yet that matches your inquiry, feel free to create a new one. Please make sure you receive themails that github sends if we comment on the issue in case we need more information. For bugs, pleaseprovide all the information necessary, like the operating system you’re using, the full error messageor any other logs, a description what you did to trigger the bug and what the actual bug was, andanything else that might be of interest. We can only help if you precisely tell us what the actual problemis, obviously.
5.2 Mail
For users of our framework, there is a mailing list for support inquiries on Google Groups. Use this listif you have issues with your Kivy-based app. Also, we have a mailing list for matters that deal withdevelopment of the actual Kivy framework code on Google Groups.
5.3 IRC
#kivy on irc.freenode.net
IRC is great for real-time communication, but please make sure to wait after you asked your question.If you just join, ask and quit we have no way of knowing who you were and where we’re supposedto send our answer to. Also, keep in mind we’re mostly based in Europe, so take into account anytimezone issues. If you’re unlucky more than once, try the mailing list.
If you don’t have an IRC client, you can also use Freenode’s web chat, but please, don’t close the browserwindow too soon. Just enter #kivy in the channels field.
23
24
Part II
API REFERENCE
The API reference is a lexicographic list of all the different classes, methods and features that Kivyoffers.
25
26
CHAPTER
SIX
KIVY FRAMEWORK
Kivy is an open source library for developing multi-touch applications. It is completely cross-platform(Linux/OSX/Win) and released under the terms of the GNU LGPL.
It comes with native support for many multi-touch input devices, a growing library of multi-touchaware widgets, hardware accelerated OpenGL drawing, and an architecture that is designed to let youfocus on building custom and highly interactive applications as quickly and easily as possible.
Thanks to Kivy’s pure Python interface, you can take advantage of its highly dynamic nature and useany of the thousands of high quality Python libraries out there. At the same time, performance-criticalsections are internally implemented on the C-level to maximize performance.
See http://kivy.org for more information.
kivy.require(version)Require can be used to check the minimum version require to run a Kivy application. For example,you can start your application like this:
import kivykivy.require(’1.0.1’)
If you don’t have a kivy version that fit the minimum required for running the application, it willraise an Exception.
Note: The Kivy version is builded like this:
X.Y.Z[-tag[-tagrevision]]
X is the Major versionY is the Minor versionZ is the Bugfixes revision
The tag in Kivy version is optionnal, but may be one of ‘dev’, ‘alpha’, ‘beta’. The tagrevision inKivy version if the revision of the tag.
Warning: You must not ask for a revision with a tag, except -dev. Asking for a ‘dev’ versionwill just warn the user if the current kivy version is not a dev, it will never launch an exception.You must not ask for a revision with a tagrevision.
kivy.kivy_configure()Call post-configuration of Kivy. This function must be called in case of you create yourself thewindow.
kivy.kivy_register_post_configuration(callback)Register a function to be call when kivy_configure() will be called.
27
Warning: Internal use only.
kivy.kivy_optionsGlobal settings options for kivy
kivy.kivy_base_dirKivy directory
kivy.kivy_libs_dirKivy external libraries directory
kivy.kivy_modules_dirKivy modules directory
kivy.kivy_data_dirKivy data directory
kivy.kivy_shader_dirKivy glsl shader directory
kivy.kivy_providers_dirKivy input provider directory
kivy.kivy_icons_dirKivy icons config path (don’t remove last ‘’)
kivy.kivy_home_dirKivy user-home storage directory
kivy.kivy_config_fnKivy configuration filename
kivy.kivy_usermodules_dirKivy user modules directory
6.1 Animation
These classes are intended to be used on a Widget. If you want to add animations to your application,you need to follow two steps:
• First, setup the animation object
• Then, use the animation on one or multiple widgets
6.1.1 Simple animation
You can animate multiple properties at the same time, with custom transition function. Here is anexample to animate the widget on a custom position and size, using ‘in_quad’ transition
widget = Widget()animation = Animation(x=50, size=(80, 80), t=’in_quad’)animation.start(widget)
6.1.2 Sequential animation
Multiple animation can be added. The result will be animated in sequential
28
widget = Widget()animation = Animation(x=50) + Animation(size=(80, 80))animation.start(widget)
6.1.3 Parallel animation
You can join one or multiple animation in parallel. This can be used when you want to use differentssettings for each properties
widget = Widget()animation = Animation(pos=(80, 10))animation &= Animation(size=(800, 800), duration=2.)
class kivy.animation.Animation(**kw)Bases: kivy.event.EventDispatcher
Create an animation definition, that can be used to animate a widget
Parameters
duration or d: float, default to 1. Duration of the animation
transition or t: str or func Transition function for animate properties
Events
on_start: widget Fired when the animation is started on a widget
on_complete: widget Fired when the animation is completed or stopped on a wid-get
on_progress: widget, progression Fired when the progression of the animation ischanging
durationReturn the duration of the animation
propertiesReturn the properties used to animate
start(widget)Start the animation on a widget
stop(widget)Stop the animation previously applied on a widget
static stop_all(widget, *largs)Stop all animations that concern a specific widget / list of properties.
Example
widget = Widget()animation = Animation(x=50)animation.start(widget)
# and laterAnimation.stop_all(widget, ’x’)
stop_property(widget, prop)Even if a animation is going, remove a property for beeing animated.
transitionReturn the transition of the animation
29
class kivy.animation.AnimationTransitionBases: object
Collection of animation function, to be used with Animation object. Eas-ing Functions ported into Kivy from Clutter Project http://www.clutter-project.org/docs/clutter/stable/ClutterAlpha.html
6.2 Application
The App class is the base for creating Kivy applications. Think of it as your main entry point into theKivy runloop. In most cases, you subclass this class and make your own app. You create an instance ofyour specific app class and then, when you are ready to start the application’s life cycle, you call yourinstance’s App.run() method.
6.2.1 Create an application by overidding build()
To initialize your app with a widget tree, override the build() method in your app class and return thewidget tree you constructed.
Here’s an example of very simple application that just shows a button:
from kivy.app import Appfrom kivy.uix.button import Button
class TestApp(App):def build(self):
return Button(text=’hello world’)
if __name__ == ’__main__’:TestApp().run()
Check kivy/examples/application/app_with_build.py.
6.2.2 Create an application with kv file
You can also use the Kivy language for creating application. The .kv can contain rules and root widgetdefinitions at the same time. Here is the same example as the Button one in a kv file.
Content of ‘test.kv’:
#:kivy 1.0
Button:text: ’Hello world’
Content of ‘main.py’:
from kivy.app import App
class TestApp(App):pass
if __name__ == ’__main__’:TestApp().run()
Check kivy/examples/application/app_with_kv.py.
The relation between main.py and test.kv is explained in App.load_kv().
30
class kivy.app.App(**kwargs)Bases: kivy.event.EventDispatcher
Application class, see module documentation for more informations.
Events
on_start: Fired when the application is beeing started (before the runTouchApp()call.
on_stop: Fired when the application stop.
build()Initializes the application, will be called only once. If this method returns a widget (tree), itwill be used as the root widget and added to the window.
load_kv()If the application have never been built, try to found the kv of the application in the samedirectory as the application class.
For example, if you have a file named main.py that contains:
class ShowcaseApp(App):pass
The load_kv() will search for a filename named showcase.kv in the directory of the main.py.The name of the kv file is the lower name of the class, without the App at the end if exist.
You can define rules and root widget in your kv file:
<ClassName>: # this is a rule...
ClassName: # this is a root widget...
You cannot declare a root widget twice. Check Kivy language documentation for more in-formation about how to create kv files. If your kv file return a root widget, it will be set inself.root
on_start()Event handler for the on_start event, which is fired after initialization (after build() has beencalled), and before the application is being run.
on_stop()Event handler for the on_stop event, which is fired when the application has finished running(e.g. the window is about to be closed).
rootRoot widget setted by the build() method or by the load_kv() method if the kv filereturn a root widget.
run()Launches the app in standalone mode.
stop(*largs)Stop the application.
If you use this method, the whole application will stop by using stopTouchApp() call.
31
6.3 Event loop management
kivy.base.EventLoopEventLoop instance
kivy.base.ExceptionManagerKivy Exception Manager instance
class kivy.base.ExceptionHandlerBase handler that catch exception in runTouchApp(). You can derivate and use it like this
class E(ExceptionHandler):def handle_exception(self, inst):
Logger.exception(inst)return ExceptionManager.PASS
ExceptionManager.add_handler(E())
All exceptions will be set to PASS, and logged to console !
handle_exception(exception)Handle one exception, default return ExceptionManager.STOP
kivy.base.runTouchApp(widget=None, slave=False)Static main function that starts the application loop. You got some magic things, if you are usingargument like this :
Parameters
<empty> To make dispatching work, you need at least one input listener. If not,application will leave. (MTWindow act as an input listener)
widget If you pass only a widget, a MTWindow will be created, and your widgetwill be added on the window as the root widget.
slave No event dispatching are done. This will be your job.
widget + slave No event dispatching are done. This will be your job, but we aretrying to get the window (must be created by you before), and add the widgeton it. Very usefull for embedding Kivy in another toolkit. (like Qt, check kivy-designed)
kivy.base.stopTouchApp()Stop the current application by leaving the main loop
6.4 Cache manager
The cache manager can be used to store python object attached to an uniq key. The cache can be con-trolled in different manner, with a object limit or a timeout.
For example, we can create a new cache with a limit of 10 objects and a timeout of 5 seconds:
# register a new CacheCache.register(’mycache’, limit=10, timeout=5)
# create an object + idtext = ’objectid’instance = Label(text=text)Cache.append(’mycache’, text, instance)
32
# retrieve the cached objectinstance = Cache.get(’mycache’, label)
If the instance is NULL, the cache may have trash it, because you’ve not used the label since 5 seconds,and you’ve reach the limit.
class kivy.cache.CacheBases: object
See module documentation for more information.
static append(category, key, obj, timeout=None)Add a new object in the cache.
Parameters
category [str] Identifier of the category
key [str] Uniq identifier of the object to store
obj [object] Object to store in cache
timeout [double (optionnal)] Custom time to delete the object if it’s not used.
static get(category, key, default=None)Get a object in cache.
Parameters
category [str] Identifier of the category
key [str] Uniq identifier of the object to store
default [anything, default to None] Default value to be returned if key is notfound
static get_lastaccess(category, key, default=None)Get the object last access time in cache.
Parameters
category [str] Identifier of the category
key [str] Uniq identifier of the object to store
default [anything, default to None] Default value to be returned if key is notfound
static get_timestamp(category, key, default=None)Get the object timestamp in cache.
Parameters
category [str] Identifier of the category
key [str] Uniq identifier of the object to store
default [anything, default to None] Default value to be returned if key is notfound
static print_usage()Print the cache usage on the console
static register(category, limit=None, timeout=None)Register a new category in cache, with limit
Parameters
category [str] Identifier of the category
33
limit [int (optionnal)] Maximum number of object in the cache. If None, no limitis applied.
timeout [double (optionnal)] Time to delete the object when it’s not used. ifNone, no timeout is applied.
static remove(category, key=None)Purge the cache
Parameters
category [str (optionnal)] Identifier of the category
key [str (optionnal)] Uniq identifier of the object to store
6.5 Clock object
The Clock object allow you to schedule a function call. The scheduling can be repetitive or just once.
You can add new event like this:
def my_callback(dt):pass
# call my_callback every 0.5 secondsClock.schedule_interval(my_callback, 0.5)
# call my_callback in 5 secondsClock.schedule_once(my_callback, 5)
# call my_callback as soon as possible (usually next frame.)Clock.schedule_once(my_callback)
Note: If the callback return False, the schedule will be removed.
kivy.clock.ClockInstance of the ClockBase, available for everybody
class kivy.clock.ClockBaseBases: object
A clock object, that support events
frametimeTime spended between last frame and current frame (in seconds)
get_boottime()Get time in seconds from the application start
get_fps()Get the current FPS calculated by the clock
get_rfps()Get the current “real” FPS calculated by the clock. This counter reflect the real frame dis-played on the screen.
In contrary to get_fps(), this function return a counter of the number of frame, not a averageof frame per seconds
get_time()Get the last tick made by the clock
34
schedule_interval(callback, timeout)Schedule a event to be call every <timeout> seconds
schedule_once(callback, timeout=0)Schedule an event in <timeout> seconds
tick()Advance clock to the next step. Must be called every frame. The default clock have the tick()function called by Kivy
tick_draw()Tick the drawing counter
unschedule(callback)Remove a previous schedule event
6.6 Configuration object
Config object is an instance of a modified Python ConfigParser. See ConfigParser documentation formore information.
6.6.1 Usage of Config object
Read a configuration token from a particular section:
>>> from kivy.config import Config>>> Config.getint(’kivy’, ’show_fps’)0
Change the configuration and save it:
>>> Config.set(’kivy’, ’retain_time’, 50)>>> Config.write()
6.6.2 Available configuration tokens
kivy
log_level: (debug, info, warning, error, critical) Set the minimum log level to use
log_dir: string Path of log directory
log_name: string Format string to use for the filename of log file
log_enable: (0, 1) Activate file logging
postproc
double_tap_time: int Time allowed for the detection of double tap, in milliseconds
double_tap_distance: float Maximum distance allowed for a double tap, normalizedinside the range 0 - 1000
retain_time: int Time allowed for a retain touch, in milliseconds
retain_distance: int If the touch moves more than is indicated by retain_distance, itwill not be retained. Argument should be an int between 0 and 1000.
jitter_distance: int Maximum distance for jittering detection, normalized inside therange 0 - 1000
35
jitter_ignore_devices: string, seperated with comma List of devices to ignore from jit-tering detection
ignore: list of tuples List of regions where new touches are ignored. This configura-tion token can be used to resolve hotspot problems with DIY hardware. The formatof the list must be:
ignore = [(xmin, ymin, xmax, ymax), ...]
All the values must be inside 0 - 1 range.
graphics
maxfps: int, default to 60 Maximum FPS allowed.
fullscreen: (0, 1, fake, auto) Activate fullscreen. If set to 1, the fullscreen will use a reso-lution of width times height pixels. If set to auto, the fullscreen will use your currentdisplay’s resolution instead. This is most likely what you want. If you want toplace the window in another display, use fake and adjust width, height, top and left.
width: int Width of the Window, not used if in auto fullscreen
height: int Height of the Window, not used if in auto fullscreen
fbo: (hardware, software, force-hardware) Select the FBO backend to use.
show_cursor: (0, 1) Show the cursor on the screen
position: (auto, custom) Position of the window on your display. If auto is used, youhave no control about the initial position: top and left are ignored.
top: int Top position of the Window
left: int Left position of the Window
window_icon: string Path of the window icon. Use this if you want to replace thedefault pygame icon.
rotation: (0, 90, 180, 270) Rotation of the Window
input Input section is particular. You can create new input device with this syntax:
# example of input provider instanceyourid = providerid,parameters
# example for tuio providerdefault = tuio,127.0.0.1:3333mytable = tuio,192.168.0.1:3334
See Also:
Check all the providers in kivy.input.providers for the syntax to use inside the config-uration file.
widgets
list_trigger_distance: int Maximum distance to trigger theon_touch_down/on_touch_up on child for every List widget. The value isin pixels.
list_friction: int Friction factor. 1 mean no friction.
list_friction_bound: int If one side of the list have been hit by the user, you have thepossibility to reduce the friction to use. Prefer a value below the list_friction token.
36
keyboard_type: (real, virtual) Type of the keyboard to use. If set to real, no virtual key-board will be shown on the screen. You will have to use your hardware keyboardto enter text.
modules You can activate modules with this syntax:
modulename =
Anything after the = will be passed to the module as arguments. Check the specificmodule’s documentation for a list of accepted arguments.
kivy.config.ConfigKivy configuration object
class kivy.config.KivyConfigParserBases: ConfigParser.ConfigParser
Enhanced ConfigParser class, that support the possibility of add default sections and default val-ues.
adddefaultsection(section)Add a section if the section is missing.
getdefault(section, option, defaultvalue)Get an option. If not found, it will return the defaultvalue
setdefault(section, option, value)Set the default value on a particular option
write()Write the configuration to the default kivy file
6.7 Event dispatcher
All objects that produce events in Kivy implement EventDispatcher, providing a consistent interfacefor registering and manipulating event handlers.
class kivy.event.EventDispatcherBases: object
Generic event dispatcher interface
See the module docstring for usage.
bindBind an event type or a property to a callback
Usage:
# With propertiesdef my_x_callback(obj, value):
print ’on object’, obj’, ’x changed to’, valuedef my_width_callback(obj, value):
print ’on object’, obj, ’width changed to’, valueself.bind(x=my_x_callback, width=my_width_callback)
# With eventself.bind(on_press=self.my_press_callback)
dispatchDispatch an event across all the handler added in bind(). As soon as a handler return True,the dispatching stop
37
register_event_typeRegister an event type with the dispatcher.
Registering event types allows the dispatcher to validate event handler names as they areattached, and to search attached objects for suitable handlers. Each event type declarationmust :
1.start with the prefix on_
2.have a default handler in the class
Example of creating custom event:
class MyWidget(Widget):def __init__(self, **kwargs):
super(MyWidget, self).__init__(**kwargs)self.register_event_type(’on_swipe’)
def on_swipe(self):pass
def on_swipe_callback(*largs):print ’my swipe is called’, largs
w = MyWidget()w.dispatch_event(’on_swipe’)
unbindUnbind properties from callback functions.
Same usage as bind().
unregister_event_typesUnregister an event type in the dispatcher
6.8 Factory object
The factory can be used to automatically import any class from a module, by specifying the module toimport instead of the class instance.
The class list and available modules are automatically generated by setup.py.
Example for registering a class/module:
>>> from kivy.factory import Factory>>> Factory.register(’Widget’, module=’kivy.uix.widget’)>>> Factory.register(’Vector’, module=’kivy.vector’)
Example of using the Factory:
>>> from kivy.factory import Factory>>> widget = Factory.Widget(pos=(456,456))>>> vector = Factory.Vector(9, 2)
kivy.factory.FactoryFactory instance to use for getting new classes
6.9 Gesture recognition
You can easily use these class to create new gesture, and compare them:
38
from kivy.gesture import Gesture, GestureDatabase
# Create a gestureg = Gesture()g.add_stroke(point_list=[(1,1), (3,4), (2,1)])g.normalize()
# Add him to databasegdb = GestureDatabase()gdb.add_gesture(g)
# And for the next gesture, try to find him !g2 = Gesture()# ...gdb.find(g2)
class kivy.gesture.Gesture(tolerance=None)A python implementation of a gesture recognition algorithm by Oleg Dopertchouk:http://www.gamedev.net/reference/articles/article2039.asp
Implemented by Jeiel Aranal (chemikhazi@gmail.com), released into the public domain.
add_stroke(point_list=None)Adds a stroke to the gesture and returns the Stroke instance. Optional point_list argument isa list of the mouse points for the stroke.
dot_product(comparison_gesture)Calculates the dot product of the gesture with another gesture
get_rigid_rotation(dstpts)Extract the rotation to apply to a group of points to minimize the distance to a second groupof points. The two groups of points are assumed to be centered. This is a simple version thatjust pick an angle based on the first point of the gesture.
get_score(comparison_gesture, rotation_invariant=True)Returns the matching score of the gesture against another gesture
normalize(stroke_samples=32)Runs the gesture normalization algorithm and calculates the dot product with self
class kivy.gesture.GestureDatabaseBases: object
Class to handle a gesture database.
add_gesture(gesture)Add a new gesture in database
find(gesture, minscore=0.90000000000000002, rotation_invariant=True)Find current gesture in database
gesture_to_str(gesture)Convert a gesture into a unique string
str_to_gesture(data)Convert a unique string to a gesture
class kivy.gesture.GestureStrokeGestures can be made up of multiple strokes
add_point(x, y)add_point(x=x_pos, y=y_pos) Adds a point to the stroke
39
center_stroke(offset_x, offset_y)Centers the stroke by offseting the points
normalize_stroke(sample_points=32)Normalizes strokes so that every stroke has a standard number of points. Returns True ifstroke is normalized, False if it can’t be normalized. sample_points control the resolution ofthe stroke.
points_distance(point1, point2)points_distance(point1=GesturePoint, point2=GesturePoint) Returns the distance betweentwo GesturePoint
scale_stroke(scale_factor)scale_stroke(scale_factor=float) Scales the stroke down by scale_factor
stroke_length(point_list=None)Finds the length of the stroke. If a point list is given, finds the length of that list.
6.10 Kivy language
Kivy language is a language dedicated for describing user interface and interactions. You could com-pare this language to QML of Qt (http://qt.nokia.com), but we are including new concept like the rulesdefinitions, templating and so on.
6.10.1 Overview
The language permit you to create:
Rule The rule is like CSS rules. You create a rule to match a specific class or widget in yourtree. You can automatically create interactions or adding graphicals instructions to aspecific widget (like all the widgets with the attribute cls=test).
Root widget You can use the language to create your user interface. A kv file can containonly one root widget.
Template This will be used to create part of your application, like the list content. If youwant to design the look of an entry in a list (icon in the left, text in the right), you willuse Template for that.
For the moment, templating are not yet designed in the language, we are still workingon it. Check the issue #17 (https://github.com/tito/kivy/issues#issue/17)
6.10.2 Syntax of a kv file
A kivy language file must be ended by the .kv extension.
The content of the file must always start with the kivy header, where version must be replaced with thekivy language version you’re using. For now, use 1.0:
#:kivy ‘version‘
‘content‘
The content can contain rules, root widget and template:
# syntax of a rule<Rule1,Rule2>:
.. definitions ..
40
<Rule3>:.. definitions ..
# syntax for creating a root widgetRootClassName:
.. definitions ..
Whatever is it’s an rule, root widget or template, the definition should look like this:
<ClassName>:prop1: value1prop2: value2
canvas:CanvasInstruction1:
canvasprop1: value1CanvasInstruction2:
canvasprop2: value2
AnotherClass:prop3: value1
prop1 and prop2 are the properties of ClassName and prop3 is the property of AnotherClass. If the propertydoesn’t exist in the class, an ObjectProperty will be automatically created and added to the instance.
AnotherClass will be created and added as a child of ClassName instance.
• The indentation is important, and must be 4 spaces. Tabs are not allowed.
• The value of a property must be single line. (we may change this in a future
version.) - The canvas property is special: you can put graphics class inside it to create your graphicalrepresentation of the current class.
Here is an example of a kv file that contain a root widget:
#:kivy 1.0
Button:text: ’Hello world’
6.10.3 Value expression and reserved keyword
The value is a python expression. This expression can be static or dynamic, that’s mean the value canuse the values of other properties using reserved keywords.
self The keyword self reference the “current widget instance”:
Button:text: ’My state is %s’ % self.state
root This keyword is available only in rules definition, and represent the root widget of therule (the first instance of the rule):
<Widget>:custom: ’Hello world’Button:
text: root.custom
Also, if a class definition contain an id, you can use it as a keyword:
41
<Widget>:Button:
id: ’btn1’Button:
text: ’The state of btn1 is %s’ % btn1.state
Please note that the id will be not available in the Widget instance: the id attribute will be not used.
6.10.4 Relation between values and properties
When you use kv language, we are doing magical stuff to automatically get things work. You mustknow that Properties implement the observer pattern: you can bind your own function to be calledwhen the value of a property change.
Kv language detect properties in your value, and create callback to automatically update the propertyfrom your expression.
Simple example of using a property:
Button:text: str(self.state)
In this example, we are detecting self.state as a dynamic value. Since the state of the button can changeat every moment, we are binding this value expression to the state property of the Button. Everytimethe button state changed, the text property will be updated.
Since the value is a python expression, you could do something more interesting like:
Button:text: ’Plop world’ if self.state == ’normal’ else ’Release me!’
The Button text change with the state of the button. By default, the button text will be ‘Plop world’, andwhen the button is pressed, the text will change to ‘Release me!’
6.10.5 Graphical instructions
The graphical instructions is a special part of the kv language. This concern the ‘canvas’ propertydefinition:
Widget:canvas:
Color:rgb: (1, 1, 1)
Rectangle:size: self.sizepos: self.pos
All the classes added inside the canvas property are inherith from the Instruction class. You cannotput any Widget class inside the canvas property.
If you want to do theming, you’ll have the same problem as CSS: you don’t know which rule have beenexecuted before. For our case, the rule are executed in processing order.
If you want to change of a Button is rendered, you can create your own kv, and put something like this:
<Button>canvas:
Color:rgb: (1, 0, 0)
Rectangle:
42
pos: self.possize: self.size
Rectangle:pos: self.possize: self.texture_sizetexture: self.texture
It will result a button with a red background, and the label texture in the bottom left.... in addition toall the precedent rules. You can clear all the previous instructions by using the Clear command:
<Button>canvas:
ClearColor:
rgb: (1, 0, 0)Rectangle:
pos: self.possize: self.size
Rectangle:pos: self.possize: self.texture_sizetexture: self.texture
Then, only your rules will be taken.
kivy.lang.BuilderMain instance of a BuilderBase.
class kivy.lang.BuilderBaseBases: object
Kv object are able to load Kv file or string, return the root object of the file, and inject rules in therules database.
apply(widget)Apply all the Kivy rules matching the widget on the widget.
load_file(filename, **kwargs)Insert a file into the Language Builder
Parameters
rulesonly: bool, default to False If True, the Builder will raise an exception ifyou have a root widget inside the definition
load_string(string, **kwargs)Insert a string into the Language Builder
Parameters
rulesonly: bool, default to False If True, the Builder will raise an exception ifyou have a root widget inside the definition
match(widget)Return the list of the rules matching the widget
class kivy.lang.Parser(**kwargs)Bases: object
Create a Parser object to parse a Kivy file or Kivy content.
load_resource(filename)Load an external resource
43
parse(content)Parse the content of a Parser file, and return a list of root objects.
parse_level(level, lines)Parse the current level (level * 4) indentation
parse_version(line)Parse the version line. The version line is always #:kivy <version>
strip_comments(lines)Remove all comments from lines inplace. Comments need to be on a single line and not atthe end of a line. I.e., a line’s first non-whitespace character needs to be a #.
6.11 Asynchronous data loader
This is the Asynchronous Loader. You can use it to load an image and use it, even if data are not yetavailable. You must specify a default loading image for using a such loader:
from kivy import *image = Loader.image(’mysprite.png’)
You can also load image from url:
image = Loader.image(’http://mysite.com/test.png’)
If you want to change the default loading image, you can do:
Loader.loading_image = Image(’another_loading.png’)
class kivy.loader.LoaderBaseBases: object
Common base for Loader and specific implementation. By default, Loader will be the best avail-able loader implementation.
The _update() function is called every 1 / 25.s or each frame if we have less than 25 FPS.
error_imageImage used for error (readonly)
image(filename, load_callback=None, post_callback=None)Load a image using loader. A Proxy image is returned with a loading image
img = Loader.image(filename)# img will be a ProxyImage.# You’ll use it the same as an Image class.# Later, when the image is really loaded,# the loader will change the img.image property# to the new loaded image
loading_imageImage used for loading (readonly)
run(*largs)Main loop for the loader.
start()Start the loader thread/process
stop()Stop the loader thread/process
44
class kivy.loader.ProxyImage(arg, **kwargs)Bases: kivy.core.image.Image
Image returned by the Loader.image() function.
Properties
loaded: bool, default to False It can be True if the image is already cached
Events
on_load Fired when the image is loaded and changed
6.12 Logger object
Differents level are available :
• debug
• info
• warning
• error
• critical
Examples of usage:
from kivy.logger import LoggerLogger.notice(’This is a notice’)Logger.debug(’This is a notice’)
try:raise Exception(’bleh’)
except Exception, e:Logger.exception(e)
Logger can be controled in the Kivy configuration.
kivy.logger.LoggerKivy default logger instance
kivy.logger.LoggerHistoryKivy history handler
alias of HistoryHandler
6.13 Properties
The properties classes are used for creating Widget. Theses classes are supporting:
Value checker When you assign a new value to a property, the value is checked to passsome contraints implemented in class. For example, an OptionProperty will checkthat your value is inside a list of possibilities, NumericProperty will check that yourvalue is an int or double, etc.
Observer pattern You can bind your own function to the change of a Property. If youwant to be called when the pos property change, you can bind a function to it.
Better memory management The same instance of a property is shared across multiplewidget instance. The value storage is independant of the Widget.
45
class kivy.properties.NumericPropertyBases: kivy.properties.Property
Property that represent a numeric value
The NumericProperty accept only int or float.
>>> Widget.x = 42>>> print Widget.x42>>> Widget.x = "plop"
class kivy.properties.StringPropertyBases: kivy.properties.Property
Property that represent a string value.
Only string or unicode are accepted.
class kivy.properties.ListPropertyBases: kivy.properties.Property
Property that represent a list.
Only list are allowed, tuple or any other classes are forbidden.
Warning: To mark the property as changed, you must reassign a new list each time you wantto add or remove an object. Don’t rely on append(), remove() and pop() functions.
class kivy.properties.ObjectPropertyBases: kivy.properties.Property
Property that represent an Python object.
Warning: To mark the property as changed, you must reassign a new python object.
class kivy.properties.BooleanPropertyBases: kivy.properties.Property
Property that represent only boolean
class kivy.properties.BoundedNumericPropertyBases: kivy.properties.Property
Property that represent a numeric value, with the possibility of assign minimum bound and/ormaximum bound.
Parameters
min: numeric If set, minimum bound will be used, with the value of min
max: numeric If set, maximum bound will be used, with the value of max
class kivy.properties.OptionPropertyBases: kivy.properties.Property
Property that represent a string from a specific list.
If the string set in the property are not from the list passed at the creation, you will have anexception.
Parameters
options: list (not tuple.) List of available options
46
class kivy.properties.ReferenceListPropertyBases: kivy.properties.Property
Property that allow to create tuple of other properties.
For example, if x and y are NumericProperty, we can create a ReferenceListProperty forthe pos. If you change the value of pos, it will automaticly change the values of x and y. If you readthe value of pos, it will return a tuple with the value of x and y.
class kivy.properties.AliasPropertyBases: kivy.properties.Property
Create a property with a custom getter and setter.
If you don’t found a Property class that fit to your needs, you can still create Python getter andsetter, and create a property with both of them.
Exemple from the kivy/uix/widget.py
def get_right(self):return self.x + self.width
def set_right(self, value):self.x = value - self.width
right = AliasProperty(get_right, set_right, bind=(x, width))
Parameters
getter: function Function to use as a property getter
setter: function Function to use as a property setter
bind: list/tuple List of properties to observe for changes
class kivy.properties.NumericPropertyBases: kivy.properties.Property
Property that represent a numeric value
The NumericProperty accept only int or float.
>>> Widget.x = 42>>> print Widget.x42>>> Widget.x = "plop"
class kivy.properties.PropertyBases: object
Base class for build more complex property.
This class handle all the basics setter and getter, None handling, observers list, and storage initial-isation. This class should not be directly instanciated.
bindAdd a new observer to be called only when the value is changed
getReturn the value of the property
linkLink the instance with his real name.
Warning: Internal usage only.
47
When a widget definition use a Property class, the creation of the property happen, but theinstance don’t know anything about his name in the widget class
class MyWidget(Widget):uid = NumericProperty(0)
On this example, the uid will be a NumericProperty() instance, but the property instancedon’t know his name. That’s why link() is used in Widget.__new__. The link function isalso used to create the storage of the property for this specific widget instance.
setSet a new value for the property
unbindRemove the observer from our widget observer list
unlinkDestroy the storage of a widget
6.14 Resources management
Resource management can be a pain if you have multiple path and project. We are offering you 2functions for searching specific resources across a list of paths.
kivy.resources.resource_find(filename)Search a resource in list of paths. Use resource_add_path to add a custom path to search.
kivy.resources.resource_add_path(path)Add a custom path to search in
6.15 Utils
kivy.utils.intersection(set1, set2)Return intersection between 2 list
kivy.utils.difference(set1, set2)Return difference between 2 list
kivy.utils.curry(fn, *cargs, **ckwargs)Change the function signature to pass new variable.
kivy.utils.strtotuple(s)Convert a tuple string into tuple, with some security check. Designed to be used with eval()function
a = (12, 54, 68)b = str(a) # return ’(12, 54, 68)’c = strtotuple(b) # return (12, 54, 68)
kivy.utils.get_color_from_hex(s)Transform from hex string color to kivy color
kivy.utils.get_random_color(alpha=1.0)Returns a random color (4 tuple)
Parameters
alpha [float, default to 1.0] if alpha == ‘random’ a random alpha value is generated
48
kivy.utils.is_color_transparent(c)Return true if alpha channel is 0
kivy.utils.boundary(value, minvalue, maxvalue)Limit a value between a minvalue and maxvalue
kivy.utils.deprecated(func)This is a decorator which can be used to mark functions as deprecated. It will result in a warningbeing emitted the first time the function is used.
class kivy.utils.SafeListBases: list
List with clear() method
Warning: Usage of iterate() function will decrease your performance.
kivy.utils.interpolate(value_from, value_to, step=10)Interpolate a value to another. Can be useful to smooth some transition. For example
# instead of setting directlyself.pos = pos
# use interpolate, and you’ll have a nice transitionself.pos = interpolate(self.pos, new_pos)
Warning: This interpolation work only on list/tuple/double with the same dimension. Notest are done if the dimension is not the same.
6.16 Vector
The Vector represent a 2D vector (x, y). Our implementation is made in top of a Python list.
Exemple for constructing a Vector:
>>> # Construct a point at 82,34>>> v = Vector(82, 34)>>> v[0]82>>> v.x82>>> v[1]34>>> v.y34
>>> # Construct by giving a list of 2 values>>> pos = (93, 45)>>> v = Vector(pos)>>> v[0]93>>> v.x93>>> v[1]45>>> v.y45
49
6.16.1 Optimized usage
Most of time, you can use a list for arguments, instead of using a Vector. For example, if you want tohave the distance between 2 points:
a = (10, 10)b = (87, 34)
# optimized methodprint ’distance between a and b:’, Vector(a).distance(b)
# non-optimized methodva = Vector(a)vb = Vector(b)print ’distance between a and b:’, va.distance(vb)
6.16.2 Vector operators
The Vector support some numeric operator like +, -, /:
>>> Vector(1, 1) + Vector(9, 5)[10, 6]
>>> Vector(9, 5) - Vector(5, 5)[4, 0]
>>> Vector(10, 10) / Vector(2., 4.)[5.0, 2.5]
>>> Vector(10, 10) / 5.[2.0, 2.0]
You can also do in-place operations:
>>> v = Vector(1, 1)>>> v += 2>>> v[3, 3]>>> v *= 5[15, 15]>>> v /= 2.[7.5, 7.5]
class kivy.vector.Vector(*largs)Bases: list
Vector class. See module documentation for more informations
angle(a)Computes the angle between a and b, and return the angle in degrees:
>>> Vector(100, 0).angle((0, 100))-90.0
>>> Vector(87, 23).angle((-77, 10))-157.7920283010705
distance(to)Returns the distance between two points:
50
>>> Vector(10, 10).distance((5, 10))
5.
>>> a = (90, 33)>>> b = (76, 34)>>> Vector(a).distance(b)14.035668847618199
distance2(to)Returns the distance between two points squared:
>>> Vector(10, 10).distance2((5, 10))
25
dot(a)Computes the dot product of a and b:
>>> Vector(2, 4).dot((2, 2))
12
static in_bbox(point, a, b)Return a true if point is in bbox defined by a and b:
>>> bmin = (0, 0)>>> bmax = (100, 100)>>> Vector.in_bbox((50, 50), bmin, bmax)
True >>> Vector.in_bbox((647, -10), bmin, bmax) False
length()Returns the length of a vector:
>>> Vector(10, 10).length()
14.142135623730951
>>> pos = (10, 10)>>> Vector(pos).length()14.142135623730951
length2()Returns the length of a vector squared:
>>> Vector(10, 10).length2()
200
>>> pos = (10, 10)>>> Vector(pos).length2()200
static line_intersection(v1, v2, v3, v4)Finds the intersection point between the lines (1)v1->v2 and (2)v3->v4 and returns it as avector object:
>>> a = (98, 28)>>> b = (72, 33)>>> c = (10, -5)>>> d = (20, 88)
51
>>> Vector.line_intersection(a, b, c, d)[15.25931928687196, 43.911669367909241]
Warning: This is a line intersection method, not a segment intersection.
For math see: http://en.wikipedia.org/wiki/Line-line_intersection
normalize()Returns a new vector that has the same direction as vec, but has a length of one.
>>> v = Vector(88, 33).normalize()>>> v[0.93632917756904444, 0.3511234415883917]>>> v.length()1.0
rotate(angle)Rotate the vector with an angle in degrees:
>>> v = Vector(100, 0)>>> v.rotate(45)>>> v
[70.710678118654755, 70.710678118654741]
xx property is an alpha to the first element in the list:
>>> v = Vector(12, 23)>>> v[0]
12 >>> v.x 12
yy property is an alpha to the first element in the list:
>>> v = Vector(12, 23)>>> v[1]
23 >>> v.y 23
6.17 Weak Method
WeakMethod is used in Clock class, to prevent the clock of taking memory if the object is deleted. Checkexamples/core/clock_method.py for more informations.
This WeakMethod class is taken from the recipe http://code.activestate.com/recipes/81253/, based onthe nicodemus version. (thanks to him !)
class kivy.weakmethod.WeakMethod(method)Bases: object
Implementation of weakref for function and bounded method.
is_dead()Returns True if the referenced callable was a bound method and the instance no longer exists.Otherwise, return False.
52
CHAPTER
SEVEN
CORE ABSTRACTION
This module defines the abstraction layers for our core providers and their implementations. For furtherinformation, please refer to Architectural Overview and the Core Providers and Input Providers section ofthe documentation.
In most cases, you shouldn’t directly use a library that’s already covered by the core abstraction. Alwaystry to use our providers first. In case we are missing a feature or method, please let us know by openinga new Bug report instead of relying on your library.
Note: These are not widgets! These are just abstractions of the respective functionality. Forexample, you cannot add a core image to your window. You have to use the imagewidget class instead. If you’re really looking for widgets, please refer to kivy.uixinstead.
7.1 Audio
Core class for loading and play sound.
Note: Recording audio is not supported.
class kivy.core.audio.Sound(**kwargs)Bases: kivy.event.EventDispatcher
Represent a sound to play. This class is abstract, and cannot be used directly. Use SoundLoaderto load a sound !
Events
on_play [None] Fired when the sound is played
on_stop [None] Fired when the sound is stopped
filenameGet/set the filename/uri of the sound
lengthGet length of the sound (in seconds)
load()Load the file into memory
play()Play the file
seek(position)Seek to the <position> (in seconds)
53
statusGet the status of the sound (stop, play)
stop()Stop playback
unload()Unload the file from memory
volumeGet/set the volume of the sound
class kivy.core.audio.SoundLoaderLoad a sound, with usage of the best loader for a given filename. If you want to load an audio file
sound = SoundLoader.load(filename=’test.wav’)if not sound:
# unable to load this sound ?pass
else:# sound loaded, let’s play!sound.play()
static load(filename)Load a sound, and return a Sound() instance
static register(classobj)Register a new class to load sound
7.2 Camera
Core class for acquiring the camera, and convert the input to a Texture.
class kivy.core.camera.CameraBase(**kwargs)Bases: kivy.event.EventDispatcher
Abstract Camera Widget class.
Concrete camera classes must implement initialization and frame capturing to buffer that can beuploaded to gpu.
Parameters
index: int Source index of the camera.
size [tuple (int, int)] Size at which the image is drawn. If no size is specified, itdefaults to resolution of the camera image.
resolution [tuple (int, int)] Resolution to try to request from the camera. Used in thegstreamer pipeline by forcing the appsink caps to this resolution. If the cameradoesnt support the resolution a negotiation error might be thrown.
Events
on_load Fired when the camera is loaded, and the texture became available
on_frame Fired each time the camera texture is updated
indexSource index of the camera
init_camera()Initialise the camera (internal)
54
resolutionResolution of camera capture (width, height)
start()Start the camera acquire
stop()Release the camera
textureReturn the camera texture with the latest capture
7.3 Clipboard
Core class for accessing to the Clipboard. If we are not able to access to the system clipboard, a fake onewill be used.
7.4 OpenGL
Select and use the best OpenGL library available. Depending on your system, the core provider canselect an OpenGL ES or a ‘classic’ desktop OpenGL library.
7.5 Image
Core classes for loading image and convert them to Texture. The raw image data can be keep inmemory for further access.
Note: Saving image is not yet supported.
class kivy.core.image.Image(arg, **kwargs)Bases: kivy.event.EventDispatcher
Load an image, and store the size and texture.
Parameters
arg [can be str or Texture or Image object] A string is interpreted as a path to theimage to be loaded. You can also provide a texture object or an already existingimage object. In the latter case, a real copy of the given image object will bereturned.
keep_data [bool, default to False] Keep the image data when texture is created
opacity [float, default to 1.0] Opacity of the image
scale [float, default to 1.0] Scale of the image
texture_rectangle [bool, default to True] Use rectangle texture is available (if false,will use the nearest power of 2 size for texture)
texture_mipmap [bool, default to False] Create mipmap for the texture
filenameGet/set the filename of image
heightImage height
55
imageGet/set the data image object
static load(filename, **kwargs)Load an image
Parameters
filename [str] Filename of the image
keep_data [bool, default to False] Keep the image data when texture is created
read_pixel(x, y)For a given local x/y position, return the color at that position.
Warning: This function can be used only with images loaded with keep_data=True key-word. For examples
m = Image.load(’image.png’, keep_data=True)color = m.read_pixel(150, 150)
Parameters
x [int] Local x coordinate of the pixel in question.
y [int] Local y coordinate of the pixel in question.
sizeImage size (width, height)
textureTexture of the image
widthImage width
class kivy.core.image.ImageData(width, height, fmt, data)Bases: object
Container for data image : width, height, fmt and data.
Warning: Only RGB and RGBA format are allowed.
7.6 Spelling
Provide abstracted access to a range of spellchecking backends. Also provides word suggestions. TheAPI is inspired by enchant, but other backends can be added that implement the same API.
class kivy.core.spelling.SpellingBase(language=None)Bases: object
Base class for all spelling providers. Supports some abstract methods for checking words andgetting suggestions.
check(word)If word is a valid word in self._language, return True.
Parameters
word [str] The word to check. If the word is a valid word in the currently activelanguage, True is returned. If the word shouldn’t be checked, return None(e.g. for ‘’).
56
list_languages()Return a list of all languages supported by the registered languages. E.g.: [’en’, ‘en_GB’,‘en_US’, ‘de’, ...]
select_language(language)From the set of registered languages, select the first language for language.
Parameters
language [str] Language identifier. Needs to be one of the options returned bylist_languages(). Sets the language used for spell checking and word sugges-tions.
suggest(fragment)For a given fragment (i.e., part of a word or a word by itself), provide corrections (fragmentmay be misspelled) or completions as a list of strings.
Parameters
fragment [str] The word fragment to get suggestions/corrections for. E.g.: ‘foo’might become ‘of’, ‘food’ or ‘foot’.
class kivy.core.spelling.NoSuchLangErrorBases: exceptions.Exception
Exception to be raised when a specific language could not be found.
class kivy.core.spelling.NoLanguageSelectedErrorBases: exceptions.Exception
Exception to be raised when a language-using method is called but no language was selected priorto the call.
7.7 SVG
Abstraction layer for loading SVG files.
class kivy.core.svg.Svg(arg, **kwargs)Bases: object
Load and draw an SVG file.
Parameters
filename: str Path to the svg that should be loaded.
keep_data: bool, default to False Keep the raw svg data when the display list iscreated
scale: float, default to 1.0 Scale of the svg
anchor_x: float, default to 0 X anchor (x coordinate based on original width, whichwill be at x pos and used as center for scaling)
anchor_y: float, default to 0 Y anchor (y coordinate based on original height,which will be at y pos and used as center for scaling)
filenameGet/set the filename of svg
static load(filename, **kwargs)Load an Svg file
Parameters
57
filename: str Filename of the image
7.8 Text
Abstraction of text creation. Depending of the selected backend, the text rendering can be more or lessaccurate.
class kivy.core.text.LabelBase(**kwargs)Bases: object
Core text label. This is the abstract class used for different backend to render text.
Warning: The core text label can’t be changed at runtime, you must recreate one.
Parameters
font_size: int, default to 12 Font size of the text
font_name: str, default to DEFAULT_FONT Font name of the text
bold: bool, default to False Activate “bold” text style
italic: bool, default to False Activate “italic” text style
size: list, default to (None, None) Add constraint to render the text (inside abounding box) If no size is given, the label size will be set to the text size.
padding: int, default to None If it’s a integer, it will set padding_x and padding_y
padding_x: int, default to 0 Left/right padding
padding_y: int, default to 0 Top/bottom padding
halign: str, default to “left” Horizontal text alignement inside bounding box
valign: str, default to “bottom” Vertical text alignement inside bounding box
content_heightReturn the content height
content_sizeReturn the content size (width, height)
content_widthReturn the content width
fontidReturn an uniq id for all font parameters
get_extents(text)Return a tuple with (width, height) for a text.
labelGet/Set the text
refresh()Force re-rendering of the text
render(real=False)Return a tuple(width, height) to create the image with the user constraints.
2 differents methods are used:
• if user don’t set width, splitting line and calculate max width + height
• if user set a width, blit per glyph
58
textGet/Set the text
7.9 Video
Core class for reading video file and manage the kivy.graphics.texture.Texture video.
Note: Recording is not supported.
class kivy.core.video.VideoBase(**kwargs)Bases: kivy.event.EventDispatcher
VideoBase, a class to implement a video reader.
Parameters
filename [str] Filename of the video. Can be a file or an URI.
eos [str, default to ‘pause’] Action to do when EOS is hit. Can be one of ‘pause’ or‘loop’
async [bool, default to True] Asynchronous loading (may be not supported by allproviders)
autoplay [bool, default to False] Auto play the video at init
Events
on_eos Fired when EOS is hit
on_load Fired when the video is loaded, texture is available
on_frame Fired when a new frame is written on texture
durationGet the video duration (in seconds)
filenameGet/set the filename/uri of current video
load()Load the video from the current filename
play()Play the video
positionGet/set the position in the video (in seconds)
seek(percent)Move on percent position
stateGet the video playing status
stop()Stop the video playing
textureGet the video texture
unload()Unload the actual video
59
volumeGet/set the volume in the video (1.0 = 100%)
7.10 Window
Core class for create the default Kivy window. Kivy support only one window creation. Don’t try tocreate more than one.
class kivy.core.window.WindowBase(**kwargs)Bases: kivy.event.EventDispatcher
WindowBase is a abstract window widget, for any window implementation.
Warning: The parameters are not working in normal case. Because at import, Kivy create adefault OpenGL window, to add the ability to use OpenGL directives, texture creation.. beforecreating Window. If you don’t like this behavior, you can include before the very first importof Kivy
import osos.environ[’KIVY_SHADOW’] = ’0’
This will forbid Kivy to create the default window !
Parameters
fullscreen: bool Make window as fullscreen
width: int Width of window
height: int Height of window
Events
on_motion: etype, motionevent Fired when a new MotionEvent is dispatched
on_touch_down: Fired when a new touch appear
on_touch_move: Fired when an existing touch is moved
on_touch_down: Fired when an existing touch disapear
on_draw: Fired when the Window is beeing drawed
on_flip: Fired when the Window GL surface is beeing flipped
on_rotate: rotation Fired when the Window is beeing rotated
on_close: Fired when the Window is closed
on_keyboard: key, scancode, unicode, modifier Fired when the keyboard is in ac-tion
on_key_down: key, scancode, unicode Fired when a key is down
on_key_up: key, scancode, unicode Fired when a key is up
add_widget(widget)Add a widget on window
centerRotated window center
clear()Clear the window with background color
60
clearcolorColor used to clear window:
from kivy.core.window import Window
# red background color Window.clearcolor = (1, 0, 0, 1)
# don’t clear background at all Window.clearcolor = None
close()Close the window
create_window()Will create the main window and configure it.
Warning: This method is called automatically at runtime. If you call it, it will recreate aRenderContext and Canvas. This mean you’ll have a new graphics tree, and the old onewill be unusable.This method exist to permit the creation of a new OpenGL context AFTER closing the firstone. (Like using runTouchApp() and stopTouchApp()).This method have been only tested in unittest environment, and will be not suitable forApplications.Again, don’t use this method unless you know exactly what you are doing !
flip()Flip between buffers
heightRotated window height
on_close(*largs)Event called when the window is closed
on_flip()Flip between buffers (event)
on_key_down(key, scancode=None, unicode=None, modifier=None)Event called when a key is down (same arguments as on_keyboard)
on_key_up(key, scancode=None, unicode=None)Event called when a key is up (same arguments as on_keyboard)
on_keyboard(key, scancode=None, unicode=None, modifier=None)Event called when keyboard is in action
Warning: Some providers may omit scancode, unicode and/or modifier!
on_motion(etype, me)Event called when a Motion Event is received.
Parameters
etype: str One of ‘begin’, ‘update’, ‘end’
me: MotionEvent Motion Event currently dispatched
on_mouse_down(x, y, button, modifiers)Event called when mouse is in action (press/release)
on_mouse_move(x, y, modifiers)Event called when mouse is moving, with buttons pressed
on_mouse_up(x, y, button, modifiers)Event called when mouse is moving, with buttons pressed
61
on_resize(width, height)Event called when the window is resized
on_rotate(rotation)Event called when the screen have been rotated
on_touch_down(touch)Event called when a touch is down
on_touch_move(touch)Event called when a touch move
on_touch_up(touch)Event called when a touch up
release_keyboard()Internal method for widget, to release the real-keyboard. Check request_keyboard() tounderstand how it works.
remove_widget(widget)Remove a widget from window
request_keyboard(callback)Internal method for widget, to request the keyboard. This method is not intented to be usedby end-user, however, if you want to use the real-keyboard (not virtual keyboard), you don’twant to share it with another widget.
A widget can request the keyboard, indicating a callback to call when the keyboard will bereleased (or taken by another widget).
screenshot(name=’screenshot%(counter)04d.jpg’)Save the actual displayed image in a file
sizeRotated size of the window
system_sizeReal size of the window, without taking care of the rotation
toggle_fullscreen()Toggle fullscreen on window
widthRotated window width
kivy.core.window.WindowInstance of a WindowBase implementation
62
CHAPTER
EIGHT
GRAPHICS
This package assemble all low level function to draw object. The whole graphics package is compatibleOpenGL ES 2.0, and have a lot of rendering optimizations.
8.1 The basics
For drawing on a screen, you will need :
1. a Canvas object.
2. Instruction objects.
Each widget in Kivy already have by default their Canvas. When you are creating a widget, you cancreate all the instructions needed for drawing. If self is your current widget, you can do:
from kivy.graphics import *with self.canvas:
# Add a red colorColor(1., 0, 0)
# Add a rectangleRectangle(pos=(10, 10), size=(500, 500))
The instructions Color and Rectangle are automaticly added to the canvas object, and will be usedwhen the window drawing will happen.
8.2 Compilation
Todo
Write more about the compilation.
8.3 Graphics compiler
Before rendering an InstructionGroup, we are compiling the group, in order to reduce the numberof instructions executed at rendering time.
63
8.3.1 Reducing the context instructions
Imagine that you have a scheme like this
Color(1, 1, 1)Rectangle(source=’button.png’, pos=(0, 0), size=(20, 20))Color(1, 1, 1)Rectangle(source=’button.png’, pos=(10, 10), size=(20, 20))Color(1, 1, 1)Rectangle(source=’button.png’, pos=(10, 20), size=(20, 20))
The real instruction seen by the graphics canvas would be
Color: change ’color’ context to 1, 1, 1BindTexture: change ’texture0’ to ‘button.png texture‘Rectangle: push vertices (x1, y1...) to vbo & drawColor: change ’color’ context to 1, 1, 1BindTexture: change ’texture0’ to ‘button.png texture‘Rectangle: push vertices (x1, y1...) to vbo & drawColor: change ’color’ context to 1, 1, 1BindTexture: change ’texture0’ to ‘button.png texture‘Rectangle: push vertices (x1, y1...) to vbo & draw
Only the first Color and BindTexture are useful, and really change the context. We can reduce themto
Color: change ’color’ context to 1, 1, 1BindTexture: change ’texture0’ to ‘button.png texture‘Rectangle: push vertices (x1, y1...) to vbo & drawRectangle: push vertices (x1, y1...) to vbo & drawRectangle: push vertices (x1, y1...) to vbo & draw
This is what the compiler does in the first place, by flagging all the unused instruction with GI_IGNOREflag. As soon as a Color content change, the whole InstructionGroup will be recompiled, and maybe aprevious unused Color will be used at the next compilation.
Note to any Kivy contributor / internal developer:
• All context instructions are checked if they are changing anything on the
cache - We must ensure that a context instruction are needed into our current Canvas. - We must ensurethat we don’t depend of any other canvas - We must reset our cache if one of our children is anotherinstruction group, because we don’t know if they are doing weird things or not.
8.4 Context instructions
The context instructions represent non graphics elements like:
• Matrix manipulation
• Color manipulation
• Texture binding
class kivy.graphics.context_instructions.LineWidth(*args, **kwargs)Bases: kivy.graphics.instructions.ContextInstruction
Instruction to set the line width of the drawing context
class kivy.graphics.context_instructions.Color(*args, **kwargs)Bases: kivy.graphics.instructions.ContextInstruction
64
Instruction to set the color state for any vetices being drawn after it
class kivy.graphics.context_instructions.BindTexture(**kwargs)Bases: kivy.graphics.instructions.ContextInstruction
BindTexture Graphic instruction. The BindTexture Instruction will bind a texture and enableGL_TEXTURE_2D for subsequent drawing.
Parameters
texture: Texture specifies the texture to bind to the given index
sourceSet/get the source (filename) to load for texture.
class kivy.graphics.context_instructions.PushMatrix(*args, **kwargs)Bases: kivy.graphics.instructions.ContextInstruction
PushMatrix on context’s matrix stack
class kivy.graphics.context_instructions.PopMatrix(*args, **kwargs)Bases: kivy.graphics.instructions.ContextInstruction
Pop Matrix from context’s matrix stack onto model view
class kivy.graphics.context_instructions.Rotate(*args)Bases: kivy.graphics.context_instructions.Transform
Rotate the coordinate space by applying a rotation transformation on the modelview matrix. Youcan set the properties of the instructions afterwards with e.g.:
rot.angle = 90rot.axis = (0,0,1)
angleProperty for getting/settings the angle of the rotation
axisProperty for getting/settings the axis of the rotation
The format of the axis is (x, y, z).
set(float angle, float ax, float ay, float az)Set the angle and axis of rotation
>>> rotationobject.set(90, 0, 0, 1)
class kivy.graphics.context_instructions.Scale(*args)Bases: kivy.graphics.context_instructions.Transform
Instruction to perform a uniform scale transformation
scaleProperty for getting/setting the scale.
The same scale value is applied on all axis.
class kivy.graphics.context_instructions.Translate(*args)Bases: kivy.graphics.context_instructions.Transform
Instruction to create a translation of the model view coordinate space
set_translate(x, y, z)
xProperty for getting/setting the translation on X axis
65
xy2 tuple with translation vector in 2D for x and y axis
xyz3 tuple translation vector in 3D in x, y, and z axis
yProperty for getting/setting the translation on Y axis
zProperty for getting/setting the translation on Z axis
class kivy.graphics.context_instructions.MatrixInstruction(*args, **kwargs)Bases: kivy.graphics.instructions.ContextInstruction
Base class for Matrix Instruction on canvas
matrixMatrix property. Numpy matrix from transformation module setting the matrix using thisporperty when a change is made is important, becasue it will notify the context about theupdate
kivy.graphics.context_instructions.gl_init_resources()gl_init_resources()
8.5 Framebuffer
Fbo is like an offscreen window. You can activate the fbo for rendering into a texture, and use your fboas a texture for another drawing.
Fbo act as a kivy.graphics.instructions.Canvas.
Exemple of using an fbo for some color rectangles
from kivy.graphics import Fbo, Color, Rectangle
class FboTest(Widget):def __init__(self, **kwargs):
super(FboTest, self).__init__(**kwargs)
# first step is to create the fbo and use the fbo texture on other# rectangle
with self.canvas:# create the fboself.fbo = Fbo(size=(256, 256))
# show our fbo on the widget in different sizeColor(1, 1, 1)Rectangle(size=(32, 32), texture=self.fbo.texture)Rectangle(pos=(32, 0), size=(64, 64), texture=self.fbo.texture)Rectangle(pos=(96, 0), size=(128, 128), texture=self.fbo.texture)
# in the second step, you can draw whatever you want on the fbowith self.fbo:
Color(1, 0, 0, .8)Rectangle(size=(256, 64))Color(0, 1, 0, .8)Rectangle(size=(64, 256))
66
If you change anything in the self.fbo object, it will be automaticly updated, and canvas where the fbo isputted will be automaticly updated too.
class kivy.graphics.fbo.Fbo(*args, **kwargs)Bases: kivy.graphics.instructions.RenderContext
Fbo class for wrapping the OpenGL Framebuffer extension. The Fbo support “with” statement.
Parameters
clear_color: tuple, default to (0, 0, 0, 0) Define the default color for clearing theframebuffer
size: tuple, default to (1024, 1024) Default size of the framebuffer
push_viewport: bool, default to True If True, the OpenGL viewport will be set tothe framebuffer size, and will be automatically restored when the framebufferreleased.
with_depthbuffer: bool, default to True If True, the framebuffer will be allocatedwith a Z buffer.
texture: Texture, default to None If None, a default texture will be created.
bind()
Bind the FBO to the current opengl context. Bind mean that you enable the Framebuffer,and all the drawing operations will act inside the Framebuffer, until release() iscalled.
The bind/release operation are automatically done when you add graphics object in it.But if you want to manipulate a Framebuffer yourself, you can use it like this:
self.fbo = FBO()self.fbo.bind()# do any drawing commandself.fbo.unbind()
# then, your fbo texture is available atprint self.fbo.texture
clear_buffer()Clear the framebuffer with the clear_color
clear_colorClear color in (red, green, blue, alpha) format.
release()Release the Framebuffer (unbind).
sizeSize of the framebuffer, in (width, height) format.
If you change the size, the framebuffer content will be lost.
textureReturn the framebuffer texture
8.6 Canvas
The Canvas is the root object used for drawing by a Widget. Check module documentation for moreinformation about the usage of Canvas.
67
class kivy.graphics.instructions.Instruction(**kwargs)Bases: object
Represent the smallest instruction available. This class is for internal usage only, don’t use itdirectly.
class kivy.graphics.instructions.InstructionGroup(**kwargs)Bases: kivy.graphics.instructions.Instruction
Group of Instruction. Add the possibility of adding and removing graphics instruction.
add(Instruction c)Add a new Instruction in our list.
clear()Remove all the Instruction
get_group(str groupname)
Return a generator with all the Instruction from a specific group name.
insert(int index, Instruction c)Insert a new Instruction in our list at index.
remove(Instruction c)Remove an existing Instruction from our list.
remove_group(str groupname)Remove all Instruction with a specific group name.
class kivy.graphics.instructions.ContextInstruction(**kwargs)Bases: kivy.graphics.instructions.Instruction
A context instruction is the base for creating non-display instruction for Canvas (texture binding,color parameters, matrix manipulation...)
class kivy.graphics.instructions.VertexInstruction(**kwargs)Bases: kivy.graphics.instructions.Instruction
A vertex instruction is the base for creating displayed instruction for Canvas (Rectangles, Trian-gles, Lines, Ellipse...)
sourceThis property represent the filename to used for the texture. If you want to use another imageas a source, you can do:
with self.canvas:Rectangle(source=’mylogo.png’, pos=self.pos, size=self.size)
Or in a kivy language:
<MyWidget>:canvas:
Rectangle:source: ’myfilename.png’pos: self.possize: self.size
Note: The filename will be search with kivy.resources.resource_find() function.
tex_coordsThis property represent the texture coordinate used for drawing the vertex instruction. Thevalue must be a list of 8 values.
68
A texture coordinate have a position (u, v), and a size (w, h). The size can be negative, andwill represent the ‘inversed’ texture. By default, the tex_coords will be:
[u, v, u + w, v, u + w, y + h, u, y + h]
You can pass your own texture coordinate, if you want to do fancy effects.
Warning: The default value as exposed just before can be negative. Depending of theprovider of image nor label, the coordinate are flip in vertical, because of the order ofinternal image. Instead of flipping the image data, we are just flipping the texture coordi-nate to be faster.
textureProperty that represent the texture used for drawing this Instruction. You can set a newtexture like this:
from kivy.core.image import Image
texture = Image(’logo.png’).texturewith self.canvas:
Rectangle(texture=texture, pos=self.pos, size=self.size)
Usually, you will use source attribute instead of texture.
class kivy.graphics.instructions.Canvas(**kwargs)Bases: kivy.graphics.instructions.CanvasBase
Our famous Canvas class. Use this class for add graphics or context instructions to use whendrawing
Note: The Canvas support “with” statement.
Usage of Canvas without “with” statement:
self.canvas.add(Color(1., 1., 0))self.canvas.add(Rectangle(size=(50, 50)))
Usage of Canvas with the “with” statement:
with self.canvas:Color(1., 1., 0)Rectangle(size=(50, 50))
add(Instruction c)
afterProperty for getting the after group.
ask_update()
Ask the canvas to update itself the next frame. Can be useful when a texture content ischanging, but anything else in the canvas.
beforeProperty for getting the before group.
clear()
draw()Apply the instruction on our window.
remove(Instruction c)
69
class kivy.graphics.instructions.RenderContext(*args, **kwargs)Bases: kivy.graphics.instructions.Canvas
The render context store all the necessary information for drawing, aka:
•the fragment shader
•the vertex shader
•the default texture
•the state stack (color, texture, matrix...)
class kivy.graphics.instructions.Callback(arg, **kwargs)Bases: kivy.graphics.instructions.Instruction
A Callback is a instruction that will be called when the drawing happen. If you are building acanvas, you can do:
with self.canvas:Color(1, 1, 1)Rectangle(pos=self.pos, size=self.size)Callback(self.my_callback)
The definition of the callback must be:
def my_callback(self, instr):print ’I am called !’
The drawing of your canvas can not happen until something new changes. From your callback,you can ask for an update:
with self.canvas:self.cb = Canvas(self.my_callback)
# then later in the codeself.cb.ask_update()
If you are using the Callback class to call rendering method of another toolkit, you will have issueswith opengl context. The opengl state can be changed inside the another tookit, and so, as soonas you’ll back to Kivy, it will just broke. You can have glitch, crash, etc. To prevent that, you canactivate the reset_context option. It will reset the opengl context state to make Kivy renderingcorrect, after the call of your callback.
Warning: The reset_context is not a full OpenGL reset. If you have issues around that,please contact us.
ask_update()
Ask the parent canvas to update itself the next frame. Can be useful when a texture con-tent is changing, but anything else in the canvas.
reset_contextSet to True if you want to reset OpenGL context for kivy after the callback have been called.
8.7 Texture management
OpenGL texture can be a pain to manage ourself, except if you know perfectly all the OpenGL API :).
class kivy.graphics.texture.Texture(width, height, target, texid, colorfmt=’rgb’,mipmap=False, rectangle=False)
Bases: object
70
Handle a OpenGL texture. This class can be used to create simple texture or complex texturebased on ImageData.
bind()Bind the texture to current opengl state
blit_buffer(pbuffer, size=None, colorfmt=None, pos=None, bufferfmt=None)Blit a buffer into a texture.
Parameters
pbuffer [str] Image data
size [tuple, default to texture size] Size of the image (width, height)
colorfmt [str, default to ‘rgb’] Image format, can be one of ‘rgb’, ‘rgba’,‘bgr’, ‘bgra’, ‘luminance’, ‘luminance_alpha’
pos [tuple, default to (0, 0)] Position to blit in the texture
bufferfmt [str, default to ‘ubyte’] Type of the data buffer, can be one of‘ubyte’, ‘ushort’, ‘uint’, ‘byte’, ‘short’, ‘int’, ‘float’
blit_data(im, pos=None)Replace a whole texture with a image data
create()texture_create(size=None, colorfmt=None, bufferfmt=None, rectangle=False,mipmap=False) Create a texture based on size.
Parameters
size: tuple, default to (128, 128) Size of the texture
colorfmt: str, default to ‘rgba’ Internal color format of the texture. Can be‘rgba’ or ‘rgb’, ‘luminance’, ‘luminance_alpha’
‘bufferfmt’: str, default to ‘ubyte’ Internal buffer format of the texture.Can be ‘ubyte’, ‘ushort’, ‘uint’, ‘bute’, ‘short’, ‘int’, ‘float’
rectangle: bool, default to False If True, it will use special opengl com-mand for creating a rectangle texture. It’s not available on OpenGL ES,but can be used for desktop. If we are on OpenGL ES platform, thisparameter will be ignored.
mipmap: bool, default to False If True, it will automatically generatemipmap texture.
create_from_data()texture_create_from_data(im, rectangle=True, mipmap=False) Create a texture from an Im-ageData class
disable()Do the appropriate glDisable()
enable()Do the appropriate glEnable()
flip_vertical()Flip tex_coords for vertical displaying
get_region(x, y, width, height)
Return a part of the texture, from (x,y) with (width,height) dimensions
height(readonly)
id(readonly)
71
mag_filterGet/set the mag filter texture. Available values:
•linear
•nearest
Check opengl documentation for more information about the behavior of theses values :http://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexParameter.xml.
min_filterGet/set the min filter texture. Available values:
•linear
•nearest
•linear_mipmap_linear
•linear_mipmap_nearest
•nearest_mipmap_nearest
•nearest_mipmap_linear
Check opengl documentation for more information about the behavior of theses values :http://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexParameter.xml.
mipmap(readonly)
rectangle(readonly)
target(readonly)
tex_coords(opengl)
uvposGet/set the UV position inside texture
uvsizeGet/set the UV size inside texture.
Warning: The size can be negative is the texture is flipped.
width(readonly)
wrapGet/set the wrap texture. Available values:
•repeat
•mirrored_repeat
•clamp_to_edge
Check opengl documentation for more information about the behavior of theses values :http://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexParameter.xml.
class kivy.graphics.texture.TextureRegion(int x, int y, int width, int height, Texture ori-gin)
Bases: kivy.graphics.texture.Texture
Handle a region of a Texture class. Useful for non power-of-2 texture handling.
72
8.8 Transformation
This module contain a Matrix class, used for our Graphics calculation. We are supporting:
• rotation, translation, scaling matrix
• multiply matrix
• create clip matrix (with or without perspective)
• transform 3d touch on a matrix
class kivy.graphics.transformation.MatrixBases: object
Optimized matrix class for OpenGL
>>> from kivy.graphics.transformation import Matrix>>> m = Matrix()>>> print m[[ 1.000000 0.000000 0.000000 0.000000 ][ 0.000000 1.000000 0.000000 0.000000 ][ 0.000000 0.000000 1.000000 0.000000 ][ 0.000000 0.000000 0.000000 1.000000 ]]
identityMatrix.identity(self) -> Matrix Reset matrix to identity matrix (inplace)
inverseMatrix.inverse(self) -> Matrix Return the inverted matrix
multiplyMatrix.multiply(mb, Matrix ma) -> Matrix Return a new matrix of self * arg
rotateMatrix.rotate(self, double angle, double x, double y, double z) -> Matrix Rotate the matrixwith the angle (in radian), around the axis (x, y, z)
scaleMatrix.scale(self, double x, double y, double z) -> Matrix Scale the matrix
transform_pointMatrix.transform_point(self, double x, double y, double z) -> tuple
translateMatrix.translate(self, double x, double y, double z) -> Matrix Translate the matrix
view_clipMatrix.view_clip(self, double left, double right, double bottom, double top, double near,double far, int perspective) -> Matrix Create a clip matrix (inplace)
8.9 Vertex Instructions
This module include all the classes for drawing simple vertex object.
class kivy.graphics.vertex_instructions.Triangle(**kwargs)Bases: kivy.graphics.instructions.VertexInstruction
A 2d triangle.
Parameters
points: list List of point in the format (x1, y1, x2, y2, x3, y3)
73
pointsProperty for getting/settings points of the triangle
class kivy.graphics.vertex_instructions.Quad(**kwargs)Bases: kivy.graphics.instructions.VertexInstruction
A 2d quad.
Parameters
points: list List of point in the format (x1, y1, x2, y2, x3, y3, x4, y4)
pointsProperty for getting/settings points of the quads
class kivy.graphics.vertex_instructions.Rectangle(**kwargs)Bases: kivy.graphics.instructions.VertexInstruction
A 2d rectangle.
Parameters
pos: list Position of the rectangle, in the format (x, y)
size: list Size of the rectangle, in the format (width, height)
posProperty for getting/settings the position of the rectangle
sizeProperty for getting/settings the size of the rectangle
class kivy.graphics.vertex_instructions.BorderImage(**kwargs)Bases: kivy.graphics.vertex_instructions.Rectangle
A 2d border image. The behavior of the border image is similar to the concept of CSS3 border-image.
Parameters
border: list Border information in the format (top, right, bottom, left). Each valueis in pixels.
borderProperty for getting/setting the border of the class
class kivy.graphics.vertex_instructions.Ellipse(*args, **kwargs)Bases: kivy.graphics.vertex_instructions.Rectangle
A 2d ellipse.
Parameters
segments: int, default to 180 Define how much segment is needed for drawing theellipse. The drawing will be smoother if you have lot of segment.
segmentsProperty for getting/setting the number of segments of the ellipse
class kivy.graphics.vertex_instructions.Line(**kwargs)Bases: kivy.graphics.instructions.VertexInstruction
A 2d line.
Parameters
points: list List of points in the format (x1, y1, x2, y2...)
74
pointsProperty for getting/settings points of the triangle
Warning: This will always reconstruct the whole graphics from the new points list. Itcan be very CPU expensive.
class kivy.graphics.vertex_instructions.Point(**kwargs)Bases: kivy.graphics.instructions.VertexInstruction
A 2d line.
Parameters
points: list List of points in the format (x1, y1, x2, y2...)
pointsize: float, default to 1. Size of the point (1. mean the real size will be 2)
add_point(float x, float y)Add a point into the current points list.
If you intend to add multiple point, prefer to use this method, instead of reassigna new points list. Assigning a new points list will recalculate and reupload thewhole buffer into GPU. If you use add_point, it will only upload the changes.
pointsProperty for getting/settings points of the triangle
pointsizeProperty for getting/setting point size
75
76
CHAPTER
NINE
INPUT MANAGEMENT
Our input system is wide and simple at the same time. We are currently able to support natively :
• Windows multitouch event (pencil and finger)
• MacOSX touchpad
• Linux multitouch event (kernel and mtdev)
• Linux wacom driver (pencil and finger)
• TUIO
All the input management is configurable in the Kivy configuration. You can easily use many multi-touch device into one Kivy application.
When the event have been read from devices, they are dispatched through post processing module,before sending them to your application. We got also several module by default for :
• Double tap detection
• Decrease jittering
• Decrease the loose of touch on “bad” DIY hardware
• Ignore regions
9.1 Input Postprocessing
9.1.1 Dejitter
Prevent blob jittering.
A problem that is often faced (esp. in optical MT setups) is that of jitterish BLOBs caused by bad cameracharacteristics. With this module you can get rid of that jitter. You just define a threshold jitter_distancein your config, and all touch movements that move the touch by less than the jitter distance are consid-ered ‘bad’ movements caused by jitter and will be discarded.
class kivy.input.postproc.dejitter.InputPostprocDejitterBases: object
Get rid of jitterish BLOBs. Example
[postproc]jitter_distance = 0.004jitter_ignore_devices = mouse,mactouch
Configuration
77
jitter_distance: float A float in range 0-1.
jitter_ignore_devices: string A comma-seperated list of device identifiers thatshould not be processed by dejitter (because they’re very precise already).
9.1.2 Double Tap
Search touch for a double tap
class kivy.input.postproc.doubletap.InputPostprocDoubleTapBases: object
InputPostProcDoubleTap is a post-processor to check if a touch is a double tap or not. Double tapcan be configured in the Kivy config file
[postproc]double_tap_time = 250double_tap_distance = 20
Distance parameter is in 0-1000, and time is in millisecond.
find_double_tap(ref)Find a double tap touch within self.touches. The touch must be not a previous double tap,and the distance must be ok
9.1.3 Ignore list
Ignore touch in some part on screen
class kivy.input.postproc.ignorelist.InputPostprocIgnoreListBases: object
InputPostprocIgnoreList is a post-processor who remove touch in ignore list. Ignore list can beconfigured in the Kivy config file
[postproc]# Format: [(xmin, ymin, xmax, ymax), ...]ignore = [(0.1, 0.1, 0.15, 0.15)]
Ignore list coordinate are in 0-1, not in the screen width/height.
9.1.4 Retain Touch
Reuse touch to counter finger lost behavior
class kivy.input.postproc.retaintouch.InputPostprocRetainTouchBases: object
InputPostprocRetainTouch is a post-processor to delay the ‘up’ event of a touch, to reuse it undercertains conditions. This module is designed to prevent finger lost on some hardware/setup.
Retain touch can be configured in the Kivy config file
[postproc]retain_time = 100retain_distance = 50
Distance parameter is in 0-1000, and time is in millisecond.
78
9.2 Providers
9.2.1 Native support of HID input from linux kernel
Support start from 2.6.32-ubuntu, or 2.6.34.
To configure HIDInput, put in your configuration
[input]# devicename = hidinput,/dev/input/eventXX# example with Stantum MTP4.3" screenstantum = hidinput,/dev/input/event2
Note: You must have read access to the input event.
You have the possibility to use custom range for some X, Y and pressure value. On some drivers, therange reported is invalid. To fix that, you can add one of theses options on the argument line :
• invert_x : 1 to invert X axis
• invert_y : 1 to invert Y axis
• min_position_x : X minimum
• max_position_x : X maximum
• min_position_y : Y minimum
• max_position_y : Y maximum
• min_pressure : pressure minimum
• max_pressure : pressure maximum
For example, on Asus T101M, the touchscreen report a range from 0-4095 for X and Y value, but realvalue are in a range from 0-32768. You can put it on configuration
[input]t101m = hidinput,/dev/input/event7,max_position_x=32768,max_position_y=32768
9.2.2 Native support of Wacom tablet from linuxwacom driver
To configure LinuxWacom, put in your configuration
[input]pen = linuxwacom,/dev/input/event2,mode=penfinger = linuxwacom,/dev/input/event3,mode=touch
Note: You must have read access to the input event.
You have the possibility to use custom range for some X, Y and pressure value. On some drivers, therange reported is invalid. To fix that, you can add one of theses options on the argument line :
• invert_x : 1 to invert X axis
• invert_y : 1 to invert Y axis
• min_position_x : X minimum
• max_position_x : X maximum
79
• min_position_y : Y minimum
• max_position_y : Y maximum
• min_pressure : pressure minimum
• max_pressure : pressure maximum
9.2.3 Native support of MultitouchSupport framework for MacBook (MaxOSX plat-form)
9.2.4 Mouse provider implementation
On linux system, mouse provider can be annoying when used with another multitouch provider (hid-input or mtdev.). Mouse can conflict with them: a single touch can generate one event from mouseprovider and from multitouch provider.
To avoid this behavior, you can activate the “disable_on_activity” token in mouse. Then, if they are anytouch active from another provider, the mouse will be discarded. Put in your configuration
[input]mouse = mouse,disable_on_activity
9.2.5 Native support of Multitouch device on Linux, using libmtdev.
Mtdev project is a part of Ubuntu Maverick multitouch architecture. You can read more onhttp://wiki.ubuntu.com/Multitouch
To configure MTDev, it’s preferable to use probesysfs providers. Check probesysfs for more infor-mation.
Otherwise, you can put in your configuration
[input]# devicename = hidinput,/dev/input/eventXXacert230h = mtdev,/dev/input/event2
Note: You must have read access to the input event.
You have the possibility to use custom range for some X, Y and pressure value. On some drivers, therange reported is invalid. To fix that, you can add one of theses options on the argument line :
• invert_x : 1 to invert X axis
• invert_y : 1 to invert Y axis
• min_position_x : X minimum
• max_position_x : X maximum
• min_position_y : Y minimum
• max_position_y : Y maximum
• min_pressure : pressure minimum
• max_pressure : pressure maximum
• min_touch_major : width shape minimum
• max_touch_major : width shape maximum
80
• min_touch_minor : width shape minimum
• max_touch_minor : height shape maximum
9.2.6 Auto Create Input Provider Config Entry for Available MT Hardware (linuxonly).
Thanks to Marc Tardif for the probing code, taken from scan-for-mt-device.
The device discovery is done by this provider. However, the reading of input can be made by 2 otherproviders: hidinput or mtdev. mtdev is used prior to hidinput. For more information about mtdev,check mtdev.
Here is an example of auto creation
[input]# using mtdevdevice_%(name)s = probesysfs,provider=mtdev# using hidinputdevice_%(name)s = probesysfs,provider=hidinput# using mtdev with a match on namedevice_%(name)s = probesysfs,provider=mtdev,match=acer
# using hidinput with custom parameters to hidinput (all on one line)%(name)s = probesysfs,
provider=hidinput,param=min_pressure=1,param=max_pressure=99
ProbeSysfs module will enumerate hardware from /sys/class/input device, and configure hardwarewith ABS_MT_POSITION_X capability.
9.2.7 TUIO input provider implementation
class kivy.input.providers.tuio.TuioMotionEventProvider(device, args)Bases: kivy.input.provider.MotionEventProvider
Tuio provider listen to a socket, and handle part of OSC message
•/tuio/2Dcur
•/tuio/2Dobj
Tuio provider can be configured with the [‘input]‘ configuration
[input]# name = tuio,<ip>:<port>multitouchtable = tuio,192.168.0.1:3333
You can easily handle new tuio path by extending the providers like this
# Create a class to handle the new touch typeclass TuioNEWPATHMotionEvent(MotionEvent):
def __init__(self, id, args):super(TuioNEWPATHMotionEvent, self).__init__(id, args)
def depack(self, args):# Write here the depack function of args.# for a simple x, y, value, you can do this :if len(args) == 2:
self.sx, self.sy = argsself.profile = (’pos’, )
self.sy = 1 - self.sy
81
super(TuioNEWPATHMotionEvent, self).depack(args)
# Register it to tuio touch providerTuioMotionEventProvider.register(’/tuio/PATH’, TuioNEWPATHMotionEvent)
static create(oscpath, **kwargs)Create a touch from a tuio path
static register(oscpath, classname)Register a new path to handle in tuio provider
start()Start the tuio provider
stop()Stop the tuio provider
static unregister(oscpath, classname)Unregister a new path to handle in tuio provider
update(dispatch_fn)Update the tuio provider (pop event from the queue)
class kivy.input.providers.tuio.Tuio2dCurMotionEvent(device, id, args)Bases: kivy.input.providers.tuio.TuioMotionEvent
A 2dCur TUIO touch.
class kivy.input.providers.tuio.Tuio2dObjMotionEvent(device, id, args)Bases: kivy.input.providers.tuio.TuioMotionEvent
A 2dObj TUIO object.
9.2.8 Common definitions for Windows provider
This file provides common definitions of constants used for WM_Touch / WM_Pen
9.2.9 Support of WM_PEN message (Window platform)
class kivy.input.providers.wm_pen.WM_Pen(device, id, args)Bases: kivy.input.motionevent.MotionEvent
MotionEvent representing the WM_Pen event. Support pos profile
9.2.10 Support of WM_TOUCH message (Window platform)
class kivy.input.providers.wm_touch.WM_MotionEvent(device, id, args)Bases: kivy.input.motionevent.MotionEvent
MotionEvent representing the WM_MotionEvent event. Supports pos, shape and size profiles.
9.3 Motion Event Factory
Factory of MotionEvent providers.
class kivy.input.factory.MotionEventFactoryMotionEvent factory is a class who register all availables input factories. If you create a new inputfactory, don’t forget to register it
82
MotionEventFactory.register(’myproviderid’, MyInputProvider)
static get(name)Get a provider class from provider id
static list()Get a list of all providers availables
static register(name, classname)Register a input provider in the database
9.4 Motion Event
The MotionEvent is the base class used for every touch and no-touch event. This class define all theproperties and methods needed to handle 2D and 3D position, but may have more capabilities.
Note: You never create the MotionEvent yourself, this is the role of the ~kivy.input.providers.
9.4.1 Motion Event and Touch
We differentiate Motion Event and Touch event. A Touch event is a MotionEvent with the pos profile.Only theses event are dispatched all over the widget tree.
1. The MotionEvent are gathered from input providers
2. All the MotionEvent are dispatched in on_motion().
3. If a MotionEvent have a pos profile, we dispatch them in on_touch_down(),move,up.
9.4.2 Listen to Motion Event
If you want to receive all Motion Event, Touch or not, you can bind motion event from Window to yourown callbacks
def on_motion(self, etype, motionevent):# will receive all motion event.pass
Window.bind(on_motion=on_motion)
9.4.3 Profiles
A capability is the ability of a MotionEvent to store a new information, or a way to indicate what issupported by the Motion Event. For example, you can receive a Motion Event that have an angle, afiducial ID, or even a shape. You can check the profile attribute to check what is currently supportedby the Motion Event, and how to access on it.
This is a tiny list of the supported profiles by default. Check other input providers to know if they areother profiles available.
83
Profile name Descriptionangle 2D angle. Use property amarkerid Marker or Fiducial ID. Use property fidpos 2D position. Use properties x, ypos3d 3D position. Use properties x, y, zpressure Pressure of the contact. Use property pressureshape Contact shape. Use property shape
If yo want to know if the current MotionEvent have an angle
def on_touch_move(self, touch):if ’angle’ in touch.profile:
print ’The touch angle is’, touch.a
If you want to select only the fiducials
def on_touch_move(self, touch):if ’markerid’ not in touch.profile:
return
class kivy.input.motionevent.MotionEvent(device, id, args)Bases: object
Abstract class to represent a touch and no-touch object.
Parameters
id [str] uniq ID of the Motion Event
args [list] list of parameters, passed to depack() function
apply_transform_2d(transform)Apply a transformation on x, y, z, px, py, pz, ox, oy, oz, dx, dy, dz
copy_to(to)Copy some attribute to another touch object.
depack(args)Depack args into attributes in class
deviceDevice used for creating this touch
distance(other_touch)Return the distance between the current touch and another touch.
double_tap_timeIf the touch is a is_double_tap, this is the time between the previous tap and the currenttouch.
dposReturn delta between last position and current position, in the screen coordinate system(self.dx, self.dy)
dsxDelta between self.sx and self.psx, in 0-1 range.
dsyDelta between self.sy and self.psy, in 0-1 range.
dszDelta between self.sz and self.psz, in 0-1 range.
dxDelta between self.x and self.px, in window range
84
dyDelta between self.y and self.py, in window range
dzDelta between self.z and self.pz, in window range
grab(class_instance, exclusive=False)Grab this motion event. You can grab a touch if you absolutly want to receiveon_touch_move() and on_touch_up(), even if the touch is not dispatched by your parent
def on_touch_down(self, touch):touch.grab(self)
def on_touch_move(self, touch):if touch.grab_current == self:
# i receive my grabbed touchelse:
# it’s a normal touch
def on_touch_up(self, touch):if touch.grab_current == self:
# i receive my grabbed touch, i must ungrab it !touch.ungrab(self)
else:# it’s a normal touchpass
grab_currentUsed to determine which widget the touch is beeing dispatched. Check grab() function formore information.
idId of the touch, not uniq. This is generally the Id set by the input provider, like ID in TUIO. Ifyou have multiple TUIO source, the same id can be used. Prefer to use uid attribute instead.
is_double_tapIndicate if the touch is a double tap or not
is_touchTrue if the Motion Event is a Touch. Can be also verified is pos is profile.
move(args)Move the touch to another position
oposReturn the initial position of the touch in the screen coordinate system (self.ox, self.oy)
osxOrigin X position, in 0-1 range.
osyOrigin Y position, in 0-1 range.
oszOrigin Z position, in 0-1 range.
oxOrigin X position, in window range
oyOrigin Y position, in window range
ozOrigin Z position, in window range
85
pop()Pop attributes values from the stack
posReturn position of the touch in the screen coordinate system (self.x, self.y)
pposReturn the previous position of the touch in the screen coordinate system (self.px, self.py)
profileProfiles currently used in the touch
psxPrevious X position, in 0-1 range.
psyPrevious Y position, in 0-1 range.
pszPrevious Z position, in 0-1 range.
push(attrs=None)Push attributes values in attrs in the stack
push_attrs_stackAttributes to push by default, when we use push() : x, y, z, dx, dy, dz, ox, oy, oz, px, py, pz.
pxPrevious X position, in window range
pyPrevious Y position, in window range
pzPrevious Z position, in window range
scale_for_screen(w, h, p=None, rotation=0)Scale position for the screen
shapeShape of the touch, subclass of Shape. By default, the property is set to None
sposReturn the position in the 0-1 coordinate system (self.sx, self.sy)
sxX position, in 0-1 range
syY position, in 0-1 range
szZ position, in 0-1 range
time_startInitial time of the touch creation
udUser data dictionnary. Use this dictionnary to save your own data on the touch.
uidUniq ID of the touch. You can safely use this property, it will be never the same accross allexisting touches.
ungrab(class_instance)Ungrab a previous grabbed touch
86
xX position, in window range
yY position, in window range
zZ position, in window range
9.5 Motion Event Provider
Abstract class for a implement a MotionEvent provider. The implementation must support thestart(), stop() and update() methods.
class kivy.input.provider.MotionEventProvider(device, args)Bases: object
Base class for a provider.
start()Start the provider. This method is automatically called when the application is started, andif the configuration use the current provider.
stop()Stop the provider
update(dispatch_fn)Update the provider, and dispatch all the new touch event though the dispatch_fn argument.
9.6 Motion Event Shape
Represent the shape of the MotionEvent
class kivy.input.shape.ShapeBases: object
Abstract class for all implementation of a shape
class kivy.input.shape.ShapeRectBases: kivy.input.shape.Shape
Represent a rectangle shape.
87
88
CHAPTER
TEN
MODULES
UI module you can plug on any running Kivy apps.
89
90
CHAPTER
ELEVEN
UIX
The kivy.uix contain all the class for create and arrange Widgets. A widget is an element of a graphicaluser interface.
If you don’t know anything about Widget, you can start to read the Widget class and usage.
If you need to arrange widget on the screen, start reading the Layout class.
11.1 Anchor layout
This layout align his children to a border or a center: top, left, center, right...
class kivy.uix.anchorlayout.AnchorLayout(**kwargs)Bases: kivy.uix.layout.Layout
Anchor layout class. See module documentation for more informations.
anchor_xHorizontal anchor.
anchor_x is an OptionProperty, default to ‘center’. Can take a value of ‘left’, ‘center’ or‘right’
anchor_yVertical anchor.
anchor_y is an OptionProperty, default to ‘center’. Can take a value of ‘top’, ‘center’ or‘bottom’
paddingPadding between widget box and children, in pixels.
padding is a NumericProperty, default to 0.
11.2 Box Layout
Arrange widgets in a vertical or an horizontal box.
Example of a vertical layout:
layout = BoxLayout(orientation=’vertical’)btn1 = Button(text=’Hello’)btn2 = Button(text=’World’)layout.add_widget(btn1)layout.add_widget(btn2)
91
Example of a horizontal layout, with a border of 10 pixels between the layout and all the childrens, andthe first button should be 70% of the layout, and the second should be 30%.
layout = BoxLayout(spacing=10)btn1 = Button(text=’Hello’, size_hint=(.7, 1))btn2 = Button(text=’World’, size_hint=(.3, 1))layout.add_widget(btn1)layout.add_widget(btn2)
Note: The size_hint represent the size available after substracting all the fixed size. For example, if youhave 3 widgets (width is 200px, 50%, 50%), and if the layout have a width of 600px :
• the first widget width will be 200px
• the second widget width will be 300px
• the third widget width will be 300px
class kivy.uix.boxlayout.BoxLayout(**kwargs)Bases: kivy.uix.layout.Layout
Box layout class. See module documentation for more informations.
orientationOrientation of the layout.
orientation is an OptionProperty, default to ‘horizontal’. Can take a value of ‘vertical’or ‘horizontal’.
paddingPadding between widget box and children, in pixels.
padding is a NumericProperty, default to 0.
spacingSpacing is the space between each children, in pixels.
spacing is a NumericProperty, default to 0.
update_minimum_size(*largs)Calculates the minimum size of the layout.
In calculation, there must be a space for child widgets that have fixed size (size_hint ==(None, None)). There must also be at least enough space for every child layout’s minimumsize (cant be too small even if size_hint is set).
11.3 Button
The button is a Label with an action associated to it that is triggered when the button is pressed (orreleased after a click/touch). To configure the button, you can use the same properties that you can usefor the Label class:
button = Button(text=’Hello world’, font_size=14)
Attaching a callback when the button is pressed (clicked/touched)
def callback(instance):print ’The button <%s> is being pressed’ % instance.text
btn1 = Button(text=’Hello world 1’)btn1.bind(on_press=callback)
92
btn2 = Button(text=’Hello world 2’)btn2.bind(on_press=callback)
If you want to be notified every time the button state changes, you can attach to the Button.stateproperty
def callback(instance, value):print ’My button <%s> state is <%s>’ % (instance, value)
btn1 = Button(text=’Hello world 1’)btn1.bind(state=callback)
class kivy.uix.button.Button(**kwargs)Bases: kivy.uix.label.Label
Button class, see module documentation for more information.
Events
on_press Fired when the button is pressed.
on_release Fired when the button is released (i.e., the touch/click that pressed thebutton goes away).
stateState of the button, can be one of ‘normal’ or ‘down’. By default, the state of the button is‘normal’.
state is an OptionProperty.
11.4 Camera
This widget can be used to capture and display the camera on the screen. Once the widget is created,the texture inside the widget will be automatically updated.
cam = Camera()
The actual implementation use our CameraBase implementation. The camera used is the first onefound on your system. If you want to test another camera, you can select another index.
cam = Camera(index=1)
You can also select the camera resolution.
cam = Camera(resolution=(320, 240))
Warning: The camera texture is not updated as soon as you have created the object. The camerainitialization is asynchronous, it may take a little bit before the texture is created.
class kivy.uix.camera.Camera(**kwargs)Bases: kivy.uix.image.Image
Camera class. See module documentation for more informations.
indexIndex of the used camera, starting from 0.
index is a NumericProperty, default to -1 to allow auto selection.
playBoolean indicate if the camera is playing. You can start/stop the camera by setting thisproperty.
93
# start the camera playing at creationvideo = Camera(source=’movie.mkv’, play=True)
# create the camera, and start latervideo = Camera(source=’movie.mkv’)# and latervideo.play = True
play is a BooleanProperty, default to True.
resolutionPrefered resolution to use when invoking the camera. If you are using [-1, -1], the resolutionwill be the default one.
# create a camera object with the best image availablecam = Camera()
# create a camera object with an image of 320x240 if possiblecam = Camera(resolution=(320, 240))
Warning: Depending of the implementation, the camera may not respect this property.
resolution is a ListProperty, default to [-1, -1]
11.5 Float Layout
The FloatLayout class will just honor the Widget.pos_hint and Widget.size_hint attributes.
For example, if you create a FloatLayout with size of (300, 300):
layout = FloatLayout(size=(300, 300))
# by default, all widgets have size_hint=(1, 1)# So this button will have the same size as layoutbutton = Button(text=’Hello world’)layout.add_widget(button)
# if you want to create a button to be the 50% of the layout width, and 25%# of the layout height, and set position to 20, 20, you can dobutton = Button(text=’Hello world’, size_hint=(.5, .25), pos=(20, 20))
# If you want to create a button that will always be the size of layout -# 20% each sidesbutton = Button(text=’Hello world’, size_hint=(.6, .6),
pos_hint={’x’:.2, ’y’:.2})
Note: This layout can be used to start an application. Most of time, you need to want which size isyour Window.
Warning: If you are not using pos_hint, you must handle yourself the position of your childs. Meanif the float layout is moving, your must handle the moving childs too.
class kivy.uix.floatlayout.FloatLayout(**kwargs)Bases: kivy.uix.layout.Layout
Float layout class. See module documentation for more informations.
94
update_minimum_size(*largs)Calculates the minimum size of the layout.
11.6 Grid layout
Arrange widgets in a matrix
Example of a GridLayout:
layout = GridLayout(cols=3, rows=3)for i in range(9):
layout.add_widget(Label(text=str(i)))
Another example using two different widgets and some spacing:
layout = GridLayout(cols=3, rows=5, spacing=10)for i in range(9):
layout.add_widget(Label(text=str(i)))
for i in range(10,16):layout.add_widget(Button(text=str(i)))
The size_hint represent the size available after substracting all the fixed size. For example, if you have 3widgets (width is 200px, 50%, 50%), and if the layout have a width of 600px :
• the first widget width will be 200px
• the second widget width will be 300px
• the third widget width will be 300px
class kivy.uix.gridlayout.GridLayout(**kwargs)Bases: kivy.uix.layout.Layout
Grid layout class. See module documentation for more informations.
colsNumber of columns in the grid
cols is a NumericProperty, default to 0.
paddingPadding between widget box and children, in pixels.
padding is a NumericProperty, default to 0.
rowsNumber of rows in the grid
rows is a NumericProperty, default to 0.
spacingSpacing is the space between each children, in pixels.
spacing is a NumericProperty, default to 0.
uniform_heightDefine if the height of all the lines must be identical
uniform_height is a BooleanProperty, default to False.
uniform_widthDefine if the width of all the columns must be identical
uniform_width is a BooleanProperty, default to False.
95
class kivy.uix.gridlayout.GridLayoutExceptionBases: exceptions.Exception
Exception for errors in the grid layout manipulation
11.7 Image
Use an image as a Widget.
wimg = Image(source=’mylogo.png’)
11.7.1 Asynchronous loading
If you want to load your image in an asynchronous way, you may use the AsyncImage class. You canuse it for loading external images on the web.
image = AsyncImage(source=’http://mywebsite.com/logo.png’)
11.7.2 Alignement
By default, the image is centered and fitted inside the widget bounding box. If you don’t want that, wesuggest you to inherit from Image, and create your own style.
For example, if you want your image to take the same size of your widget, you can do
class FullImage(Image):pass
And in your kivy language file, you can do
<FullImage>:canvas:
Color:rgb: (1, 1, 1)
Rectangle:texture: self.texturesize: self.sizepos: self.pos
class kivy.uix.image.Image(**kwargs)Bases: kivy.uix.widget.Widget
Image class, see module documentation for more information.
image_ratioRatio of the image (width / float(height)
image_ratio is a AliasProperty, and is read-only.
norm_image_sizeNormalized image size withing the widget box.
This size will be always fitted to the widget size, and preserve the image ratio.
norm_image_size is a AliasProperty, and is read-only.
sourceFilename / source of your image.
source a StringProperty, default to None.
96
textureTexture object of the image.
Depending of the texture creation, the value will be a Texture or TextureRegion object.
texture is a ObjectProperty, default to None.
texture_sizeTexture size of the image.
Warning: The texture size is set after the texture property. So if you listen on the change totexture, the property texture_size will be not yet updated. Use self.texture.size instead.
class kivy.uix.image.AsyncImage(**kwargs)Bases: kivy.uix.image.Image
Asynchronous Image class, see module documentation for more information.
11.8 Label
The label widget is a widget for rendering text. You can use ascii strings or unicode strings.
Snippet
# hello world textl = Label(text=’Hello world’)
# multiline textl = Label(text=’Multi\nLine’)
# sizel = Label(text=’Hello world’, font_size=20)
class kivy.uix.label.Label(**kwargs)Bases: kivy.uix.widget.Widget
Label class, see module documentation for more information.
boldIndicate if you want to use the bold version of your font.
Note: Depending of your font, the bold attribute may have no impact on your text rendering.
bold is a BooleanProperty, default to False
colorText color, in the format (r, g, b, a)
color is a ListProperty, default to [1, 1, 1, 1].
font_nameFile of the font to use. The path used for the font can be a absolute path, or a relative paththat will be search with the resource_find() function.
Warning: Depending of your text provider, the font file can be ignored. But you canmostly use this without trouble.
font_name is a StringProperty, default to ‘fonts/DroidSans.ttf’.
97
font_sizeFont size of the text. The font size is in pixels.
font_size is a NumericProperty, default to 12.
halignHorizontal alignment of the text.
halign is a OptionProperty, default to ‘left’. Available options are : left, center and right.
italicIndicate if you want to use the italic version of your font.
Note: Depending of your font, the italic attribute may have no impact on your text render-ing.
italic is a BooleanProperty, default to False
paddingPadding of the text, in the format (padding_x, padding_y)
padding is a ReferenceListProperty of (padding_x, padding_y) properties.
padding_xHorizontal padding of the text, inside the widget box.
padding_x is a NumericProperty, default to 0
padding_yVertical padding of the text, inside the widget box.
padding_x is a NumericProperty, default to 0
textText of the label.
Creation of a simple hello world
widget = Label(text=’Hello world’)
If you want to create the widget with an unicode string, use
widget = Label(text=u’My unicode string’)
text a StringProperty.
text_sizeBy default, the label is not contraint to any bounding box. You can set the size constraint ofthe label creation with this property.
For example, whatever is your current widget size, if you want your label to be created in abox with width=200 and unlimited height:
Label(text=’Very big big line’, text_size=(200, None))
Note: This text_size property is the same as usersize property in Label class. (Even ifit’s named size= in constructor.)
text_size is a ListProperty instance, default to (None, None). Mean they are no sizerestriction by default.
98
textureTexture object of the text. The text is rendered after each properties changes, and storedinside this property. You can use this texture for any graphics elements.
Depending of the texture creation, the value will be a Texture or TextureRegion object.
Warning: The texture update is scheduled for the next frame. That’s mean if you reallywant the texture just after changing a property, you need to call texture_update()function before
l = Label(text=’Hello world’)# l.texture is goodl.font_size = 50# l.texture is not updated yetl.update_texture()# l.texture is good now.
texture is a ObjectProperty, default to None.
texture_sizeTexture size of the text.
Warning: The texture size is set after the texture property. So if you listen on the change totexture, the property texture_size will be not yet updated. Use self.texture.size instead.
texture_update(*largs)Force texture recreation with the current Label properties.
After this function call, the texture and :data‘texture_size‘ will be updated in this order.
valignVertical alignment of the text.
valign is a OptionProperty, default to ‘bottom’. Available options are : bottom, middleand top.
11.9 Layout
Layouts is a way to calculate and assign position of widgets. The Layout class itself cannot be useddirectly. You must use one of:
• Anchor layout : kivy.uix.anchorlayout.AnchorLayout
• Box layout : kivy.uix.boxlayout.BoxLayout
• Grid layout : kivy.uix.gridlayout.GridLayout
• Screen layout : kivy.uix.screenlayout.ScreenLayout
11.9.1 Understanding size_hint property in Widget
The size_hint is mostly used in Layout. This is the size, in percent, not in pixels. The format is:
widget.size_hint = (width_percent, height_percent)
The percent is between the range 0-1: 1 mean 100%.
So, if you want a widget width to be only the half of the parent, and his height to be the same as hisparent, you can do:
99
widget.size_hint = (0.5, 1.0)
If you don’t want to use size_hint for one of width or height, set his value to None. For example, if youwant a widget width to be 250px, and his height to 30% of his parent, you can write:
widget.size_hint = (None, 0.3)widget.width = 250
class kivy.uix.layout.Layout(**kwargs)Bases: kivy.uix.widget.Widget
Layout interface class, used to implement every layout. Check module documentation for moreinformation.
minimum_sizeMinimum size required by the layout. This property is used by Layout to perfom his layoutcalculations. If the widgets size (width or height) is smaller than the minimum size, it willbe resized to be at least minimum size.
minimum_size is a AliasProperty.
reposition_child(child, **kwargs)Force the child to be repositioned on the screen. This method is used internally in boxlayout.
11.10 Scatter
Scatter is a widget that you can translate, rotate and scale, with two or more fingers. This is the famouswidget as you can see on many multitouch demo.
11.10.1 Usage
By default, the widget itself don’t have any graphical representation. The idea is to combine Scatterwidget with other widget, like Image widget:
scatter = Scatter()image = Image(source=’sun.jpg’)scatter.add_widget(image)
11.10.2 Control interactions
You can also avoid some interaction, like rotation.
scatter = Scatter(do_rotation=False)
Or allow only translation.
scatter = Scatter(do_rotation=False, do_scale=False)
11.10.3 Automatic bring to front
If you add and manipulate multiple scatter, you can have trouble if the scatter is behind another scatter.We have a property named Scatter.auto_bring_to_front that remove and re-add the scatter inhis parent. The scatter will be on top as soon as you touch it.
100
11.10.4 Scale limitation
We are using 32 bits matrix, in double representation. That’s mean, we have limitation for scaling. Youcannot do infite scale down/up with our implementation. Generally, you don’t hit the minimum scale(because you don’t see it on the screen), but the maximum scale : 9.99506983235e+19 (2^66)
You can also limit the minimum and maximum zoom allowed.
scatter = Scatter(scale_min=.5, scale_max=3.)
class kivy.uix.scatter.Scatter(**kwargs)Bases: kivy.uix.widget.Widget
Scatter class. See module documentation for more information.
apply_angle_scale_trans(angle, scale, trans, point=[0, 0])
Update matrix transformation by adding new angle, scale and translate.
Parameters
angle [float] Rotation angle to add
scale [float] Scaling value to add
trans [Vector] Vector translation to add
point [Vector, default to (0, 0)] Point to apply transformation
apply_transform(trans, post_multiply=False, anchor=(0, 0))Transforms scatter by trans (on top of its current transformation state)
Parameters
trans: transformation matrix from transformation lib. Transformation to beapplied to the scatter widget
anchor: tuple, default to (0, 0) The point to use as the origin of the transforma-tion (uses local widget space)
post_multiply: bool, default to False If true the transform matrix is post multi-plied (as if applied before the current transform)
auto_bring_to_frontIf True, the widget will be automatically pushed on the top of parent widget list for drawing.
auto_bring_to_front is a BooleanProperty, default to True.
bboxBounding box of the widget in parent space
((x, y), (w, h))# x, y = lower left corner
bbox is a AliasProperty.
centerCreate a property with a custom getter and setter.
If you don’t found a Property class that fit to your needs, you can still create Python getterand setter, and create a property with both of them.
Exemple from the kivy/uix/widget.py
101
def get_right(self):return self.x + self.width
def set_right(self, value):self.x = value - self.width
right = AliasProperty(get_right, set_right, bind=(x, width))
Parameters
getter: function Function to use as a property getter
setter: function Function to use as a property setter
bind: list/tuple List of properties to observe for changes
do_rotationAllow rotation
do_rotation is a BooleanProperty, default to True.
do_scaleAllow scaling
do_scale is a BooleanProperty, default to True.
do_translationAllow translation on X or Y axis
do_translation is a AliasProperty of (do_translation_x + do_translation_y)
do_translation_xAllow translation on X axis
do_translation_x is a BooleanProperty, default to True.
do_translation_yAllow translation on Y axis
do_translation_y is a BooleanProperty, default to True.
posCreate a property with a custom getter and setter.
If you don’t found a Property class that fit to your needs, you can still create Python getterand setter, and create a property with both of them.
Exemple from the kivy/uix/widget.py
def get_right(self):return self.x + self.width
def set_right(self, value):self.x = value - self.width
right = AliasProperty(get_right, set_right, bind=(x, width))
Parameters
getter: function Function to use as a property getter
setter: function Function to use as a property setter
bind: list/tuple List of properties to observe for changes
rotationRotation value of the scatter
rotation is a AliasProperty.
102
scaleScale value of the scatter
scale is a AliasProperty.
scale_maxMaximum scaling factor allowed
scale_max is a NumericProperty, default to 1e20
scale_minMinimum scaling factor allowed
scale_min is a NumericProperty, default to 0.01
transformTransformation matrix
transform is a ObjectProperty, default to the identity matrix.
transform_invInverse of the transformation matrix
transform_inv is a ObjectProperty, default to the identity matrix.
xCreate a property with a custom getter and setter.
If you don’t found a Property class that fit to your needs, you can still create Python getterand setter, and create a property with both of them.
Exemple from the kivy/uix/widget.py
def get_right(self):return self.x + self.width
def set_right(self, value):self.x = value - self.width
right = AliasProperty(get_right, set_right, bind=(x, width))
Parameters
getter: function Function to use as a property getter
setter: function Function to use as a property setter
bind: list/tuple List of properties to observe for changes
yCreate a property with a custom getter and setter.
If you don’t found a Property class that fit to your needs, you can still create Python getterand setter, and create a property with both of them.
Exemple from the kivy/uix/widget.py
def get_right(self):return self.x + self.width
def set_right(self, value):self.x = value - self.width
right = AliasProperty(get_right, set_right, bind=(x, width))
Parameters
getter: function Function to use as a property getter
setter: function Function to use as a property setter
103
bind: list/tuple List of properties to observe for changes
11.11 Slider
The slider is a widget that look like a scrollbar, and support horizontal/vertical orientation, mini-mum/maximum value, and a default value.
For example, create a slider from -100 to 100, default to 25
from kivy.uix.slider import Sliders = Slider(min=-100, max=100, value=25)
Or for creating a vertical slider
from kivy.uix.slider import Sliders = Slider(orientation=’vertical’)
class kivy.uix.slider.Slider(**kwargs)Bases: kivy.uix.widget.Widget
Class for creating Slider widget.
Check module documentation for more details.
maxMaximum value allowed for value.
max is a NumericProperty, default to 100.
minMinimum value allowed for value.
min is a NumericProperty, default to 0.
orientationOrientation of the slider.
orientation is an OptionProperty, default to ‘horizontal’. Can take a value of ‘vertical’or ‘horizontal’.
paddingPadding of the slider. The padding is used for graphical representation and interaction. Itprevent the cursor to go out of the bounds of the slider bounding box.
By default, padding is 10. The range of the slider is reduced from padding * 2 on the screen.It allow to draw a cursor of 20px width, without having the cursor going out of the widget.
padding is a NumericProperty, default to 10.
rangeRange of the slider, in the format (minimum value, maximum value).
>>> slider = Slider(min=10, max=80)>>> slider.range[10, 80]>>> slider.range = (20, 100)>>> slider.min20>>> slider.max100
range is a ReferenceListProperty of (min, max)
104
valueCurrent value used for the slider.
value is a NumericProperty, default to 0.
value_normalizedNormalized value inside the range (min/max) to 0-1 range.
>>> slider = Slider(value=50, min=0, max=100)>>> slider.value50>>> slider.value_normalized0.5>>> slider.value = 0>>> slider.value_normalized0>>> slider.value = 1>>> slider.value_normalized1
You can also use it for setting the real value without knowing the minimum and maximum.
>>> slider = Slider(min=0, max=200)>>> slider.value_normalized = .5>>> slider.value100>>> slider.value_normalized = 1.>>> slider.value200
value_normalized is an AliasProperty.
value_posPosition of the internal cursor, based on the normalized value.
value_pos is an AliasProperty.
11.12 Text Input
The TextInput element displays a box of editable plain text.
This widget support by default nice features such as :
• Unicode text
• Multiline editing
• Key navigations
• Selection by keys or touch
• Clipboard support
Note: The documentation have 2 differents measurement:
• (x, y) Coordinates in pixels, mostly used for rendering on screen
• (row, col) Index in characters / lines, used for selection and cursor movement.
105
11.12.1 Usage example
Creation of a multiline textinput:
from kivy.uix.textinput import TextInputtextinput = TextInput(text=’Hello world’)
You can create a monoline textinput: the ‘enter’ key will have no impact.
textinput = TextInput(text=’Hello world’, multiline=False)
Get all the text changes:
def on_text(instance, value):print ’The widget’, instance, ’have:’, value
textinput = TextInput()textinput.bind(text=on_text)
You can ‘focus’ a textinput, mean that the input box will be highlighted, and keyboard will be requested
textinput = TextInput(focus=True)
The textinput can be leaved by escape or if another textinput is requesting the real keyboard. That’smean the widget will be ‘unfocused’. You attach to focus property, and check the current status:
def on_focus(instance, value):if value:
print ’User entered in’, instanceelse:
print ’User leaved from’, instance
textinput = TextInput()textinput.bind(focus=on_focus)
11.12.2 Selection
Selection of the textinput is automatically managed. You can get the current selection withTextInput.selection_text property. The selection is automatically updated when the cursor po-sition change.
106
11.12.3 Default shortcuts
Shortcuts DescriptionLeft Move cursor to leftRight Move cursor to rightUp Move cursor to upDown Move cursor to downHome Move cursor at the beginning of the lineEnd Move cursor at the end of the linePageUp Move cursor to 3 lines beforePageDown Move cursor to 3 lines afterBackspace Delete the selection or character before the cursorDel Delete the selection of character after the cursorShift + <dir> Start a text selection. Dir can be Up, Down, Left, RightControl + c Copy selectionControl + x Cut selectionControl + p Paste selectioncontrol + a Select all the content
class kivy.uix.textinput.TextInput(**kwargs)Bases: kivy.uix.widget.Widget
TextInput class, see module documentation for more information.
cancel_selection()Cancel current selection if any
cursorTuple of (row, col) of the current cursor position. You can set a new (row, col) if you want tomove the cursor position. The scrolling area will be automatically updated to always ensurethat the cursor will be showed inside the viewport.
cursor is a AliasProperty.
cursor_blinkThis property is used to blink the cursor graphics. The value of cursor_blink is automat-ically computed, setting a value on it will have no impact.
cursor_blink is a BooleanProperty, default to False
cursor_colCurrent column of the cursor.
cursor_col is a AliasProperty to cursor[0], read-only.
cursor_index()Return the cursor index in the text/value.
cursor_offset()Get the cursor x offset on the current line
cursor_posCurrent position of the cursor, in (x, y).
cursor_pos is a AliasProperty, read-only.
cursor_rowCurrent row of the cursor.
cursor_row is a AliasProperty to cursor[1], read-only.
delete_selection()Suppress from the value current selection if any
107
do_backspace()Do backspace operation from the current cursor position. This action might do lot of thingslike:
•removing the current selection if available
•removing the previous char, and back the cursor
•do nothing, if we are at the start.
do_cursor_movement(action)Do a cursor movement from the current cursor position. Action can be one of :
•cursor_left: move the cursor to the left
•cursor_right: move the cursor to the right
•cursor_up: move the cursor on the previous line
•cursor_down: move the cursor on the next line
•cursor_home: move the cursor at the start of the current line
•cursor_end: move the cursor at the end of current line
•cursor_pgup: move one “page” before
•cursor_pgdown: move one “page” after
Warning: Current page are 3 lines before/after
focusIf focus is true, the keyboard will be requested, and you can start to write on the textinput.
focus is a BooleanProperty, default to False
font_nameFile of the font to use. The path used for the font can be a absolute path, or a relative paththat will be search with the resource_find() function.
Warning: Depending of your text provider, the font file can be ignored. But you canmostly use this without trouble.
font_name is a StringProperty, default to ‘fonts/DroidSans.ttf’.
font_sizeFont size of the text. The font size is in pixels.
font_size is a NumericProperty, default to 10.
get_cursor_from_index(index)Return the (row, col) of the cursor from text index
get_cursor_from_xy(x, y)Return the (row, col) of the cursor from an (x, y) position.
insert_text(substring)Insert new text on the current cursor position
line_heightHeight of a line. This property is automatically computed from the font_name,font_size. Changing the line_height will have no-impact.
line_height is a NumericProperty, read-only.
108
multilineIf True, the widget will be able to do multiline lines. Without that, “enter” action will notadd a new line.
multiline is a BooleanProperty, default to True
paddingPadding of the text, in the format (padding_x, padding_y)
padding is a ReferenceListProperty of (padding_x, padding_y) properties.
padding_xHorizontal padding of the text, inside the widget box.
padding_x is a NumericProperty, default to 0. This might be changed by the currenttheme.
padding_yVertical padding of the text, inside the widget box.
padding_x is a NumericProperty, default to 0. This might be changed by the currenttheme.
scroll_xX scrolling value of the viewport. The scrolling is automatically updated when the cursoris moving or text is changing. But if you are not doing any action, you can still change thescroll_x.
scroll_x is a NumericProperty, default to 0.
scroll_yY scrolling value of the viewport. See scroll_x for more informations.
scroll_y is a NumericProperty, default to 0.
selection_colorCurrent color of the selection, in (r, g, b, a) format.
Warning: The color should always have “alpha” component different from 1, since theselection is drawed after the text.
selection_color is a ListProperty, default to [0.1843, 0.6549, 0.8313, .5]
selection_fromIf a selection is happening, or finished, this property will represent the cursor index wherethe selection start.
selection_from is a NumericProperty, default to None
selection_textCurrent content selection.
selection_text is a StringProperty, default to ‘’
selection_toIf a selection is happening, or finished, this property will represent the cursor index wherethe selection end.
selection_to is a NumericProperty, default to None
tab_widthBy default, each tab will be replaced by the size of 4 spaces on the text input widget. You canset a lower or higher value.
tab_width is a NumericProperty, default to 4.
109
textText of the widget.
Creation of a simple hello world
widget = TextInput(text=’Hello world’)
If you want to create the widget with an unicode string, use
widget = TextInput(text=u’My unicode string’)
text a StringProperty.
11.13 Toggle button
The toggle button act like a checkbox. When you touch it, his state will be ‘down’. You need to touch itagain to make his state to ‘up’.
The toggle button is also able to handle group. Only one button can be pushed in the same group. Thegroup name can be a string, or any hashable Python object.
btn1 = ToggleButton(text=’Male’, group=’sex’)btn2 = ToggleButton(text=’Female’, group=’sex’)btn3 = ToggleButton(text=’Mixed’, group=’sex’)
Only one of them could be checked.
class kivy.uix.togglebutton.ToggleButton(**kwargs)Bases: kivy.uix.button.Button
Toggle button class, see module documentation for more information.
groupGroup of the button. If None, no group will be used. group must be an hashable object, likea string.
group is a ObjectProperty
11.14 Video
You can play video files using Video widget. Depending of your Video core provider, you may be ableto play differents formats. For example, pygame video provider allow only MPEG1 on Linux and OSX.GStreamer is more versatile, and can play many other video format, as MKV, OGV, AVI, MOV, FLV...depending of the gstreamer plugins installed.
The video loading is also asynchronous. Many properties are not available until the video is loaded.The video is loaded when the texture is created.
def on_position_change(instance, value):print ’The initial position in the video is’, value
def on_duration_change(instance, value):print ’The duration of the video is’, video
video = Video(source=’PandaSneezes.avi’)video.bind(position=on_position_change,
duration=on_duration_change)
class kivy.uix.video.Video(**kwargs)Bases: kivy.uix.image.Image
Video class. See module documentation for more informations.
110
durationDuration of the video. The duration is default to -1, and set to real duration when the videois loaded.
duration is a NumericProperty, default to -1.
eosBoolean indicate if the video is done playing through the end.
eos is a BooleanProperty, default to False.
playBoolean indicate if the video is playing. You can start/stop the video by setting this property.
# start the video playing at creationvideo = Video(source=’movie.mkv’, play=True)
# create the video, and start latervideo = Video(source=’movie.mkv’)# and latervideo.play = True
play is a BooleanProperty, default to False.
positionPosition of the video between 0 and duration. The position is default to -1, and set to realposition when the video is loaded.
position is a NumericProperty, default to -1.
volumeVolume of the video, in the range 0-1. 1 mean full volume, 0 mean mute.
volume is a NumericProperty, default to 1.
11.15 Widget class
The Widget class is base class required to create a Widget. Our widget class is designed for:
Event managed The widget interaction is build on top of event. If a property change, thewidget will do something. If nothing change in the widget, nothing will be done. That’sthe main goal of the Property class.
Seperate widget and graphical representation We don’t have a draw() method. The idea isto let you the possibility to create your own graphical representation outside the widgetclass. And you’ll use all the available properties to do that. Every widget have his ownCanvas.
Bounding box / Collision Since the graphical representation is seperated, the position andsize of the widget represent his bounding box. You can check if a point is inside thewidget with Widget.collide_point(), or if a widget is colliding another widgetwith Widget.collide_widget().
11.15.1 Usage of properties
When you read the documentation, every property are described in the format:
<name> is a <property class>, default to <default value>
For example:
111
:data:‘Widget.pos‘ is a :class:‘~kivy.properties.ReferenceListProperty‘ of(:data:‘Widget.x‘, :data:‘Widget.y‘) properties.
If you want to know when a the pos attribute change (meaning when the widget move), you can bindyour own function like this:
def callback_pos(instance, value):print ’the widget’, instance, ’have moved to’, value
wid = Widget()wid.bind(pos=callback_pos)
class kivy.uix.widget.Widget(**kwargs)Bases: kivy.event.EventDispatcher
Widget class. See module documentation for more informations.
Events
on_touch_down: Fired when a new touch appear
on_touch_move: Fired when an existing touch is moved
on_touch_down: Fired when an existing touch disapear
add_widget(widget)Add a new widget as a child of current widget
Parameters
widget: Widget Widget to add in our children list.
>>> root = Widget()>>> root.add_widget(Button())>>> slider = Slider()>>> root.add_widget(slider)
bind(**kwargs)Bind properties or event to handler.
Example of usage:
def my_x_callback(obj, value):print ’on object’, obj’, ’x changed to’, value
def my_width_callback(obj, value):print ’on object’, obj, ’width changed to’, value
self.bind(x=my_x_callback, width=my_width_callback)
canvasCanvas of the widget.
The canvas is a graphics object that contain all the drawing instruction. Check Canvas formore information about usage.
centerCenter position of the widget
center is a ReferenceListProperty of (center_x, center_y)
center_xX center position of the widget
center_x is a AliasProperty of (x + width / 2.)
112
center_yY center position of the widget
center_y is a AliasProperty of (y + height / 2.)
childrenChildren list
children is a ListProperty instance, default to an empty list.
Use add_widget() and remove_widget() for manipulate children list. Don’t manipulatechildren list directly until you know what you are doing.
clear_widgets()Remove all widgets added to the widget.
clsClass of the widget, used for styling.
collide_point(x, y)Check if a point (x, y) is inside the widget bounding box.
Parameters
x: numeric X position of the point
y: numeric Y position of the point
Returns bool, True if the point is inside the bounding box
>>> Widget(pos=(10, 10), size=(50, 50)).collide_point(40, 40)True
collide_widget(wid)Check if widget (bounding box) is colliding with our widget bounding box.
Parameters
wid: Widget class Widget to collide to.
Returns bool, True if the widget is colliding us.
>>> wid = Widget(size=(50, 50))>>> wid2 = Widget(size=(50, 50), pos=(25, 25))>>> wid.collide_widget(wid2)True>>> wid2.pos = (55, 55)>>> wid.collide_widget(wid2)False
create_property(name)Create a new property at runtime.
Warning: This function is designed for the Kivy language, don’t use it in your code. Youshould declare the property in your class instead of using this method.
Parameters
name: string Name of the property
The class of the property cannot be specified, it will be always an ObjectProperty class.The default value of the property will be None, until you set a new value.
>>> mywidget = Widget()>>> mywidget.create_property(’custom’)>>> mywidget.custom = True
113
>>> print mywidget.customTrue
get_parent_window()Return the parent window
Returns Instance of the root window. Can be WindowBase or Widget
get_root_window()Return the root window
Returns Instance of the root window. Can be WindowBase or Widget
getter(name)Return the getter of a property.
heightHeight of the widget.
height is a NumericProperty, default to 100.
idUniq identifier of the widget in the tree.
id is a StringProperty, default to None.
Warning: If the id is already used in the tree, an exception will occur.
on_touch_down(touch)Receive a touch down event
Parameters
touch: MotionEvent class Touch received
Returns bool. If True, the dispatching will stop.
on_touch_move(touch)Receive a touch move event.
See on_touch_down() for more information
on_touch_up(touch)Receive a touch up event.
See on_touch_down() for more information
parentParent of the widget
parent is a ObjectProperty instance, default to None.
The parent of a widget is set when the widget is added to another one, and unset when thewidget is removed from his parent.
posPosition of the widget.
pos is a ReferenceListProperty of (x, y) properties.
pos_hintPosition hint. This property permit you to set the position of the widget inside his parentlayout, in percent.
For example, if you want to set the top of the widget to be at 90% height of his parent layout,you can write:
114
widget = Widget(pos_hint={‘top’: 0.9})
The keys ‘x’, ‘right’, ‘center_x’, will use the parent width. The keys ‘y’, ‘top’, ‘center_y’, willuse the parent height.
Check Float Layout for more informations.
Position hint is only used in FloatLayout and Window.
pos_hint is a ObjectProperty containing a dict.
remove_widget(widget)Remove a widget from the children of current widget
Parameters
widget: Widget Widget to add in our children list.
>>> root = Widget()>>> button = Button()>>> root.add_widget(button)>>> root.remove_widget(button)
rightRight position of the widget
right is a AliasProperty of (x + width)
setter(name)Return the setter of a property. Useful if you want to directly bind a property to another.
For example, if you want to position one widget next to you
self.bind(right=nextchild.setter(’x’))
sizeSize of the widget.
size is a ReferenceListProperty of (width, height) properties.
size_hintSize hint.
size_hint is a ReferenceListProperty of (size_hint_x, size_hint_y)
See size_hint_x for more information
size_hint_xX size hint. It represent how much space the widget should use in the X axis from his parent.Only Layout and Window are using the hint.
Value is in percent, 1. will mean the full size of his parent, aka 100%. 0.5 will represent 50%.
size_hint_x is a NumericProperty, default to 1.
size_hint_yY size hint.
size_hint_y is a NumericProperty, default to 1.
See size_hint_x for more information
to_local(x, y, relative=False)Transform parent coordinate to local coordinate
Parameters
relative: bool, default to False Change to True is you want to translate a coor-dinate to a relative coordinate from widget.
115
to_parent(x, y, relative=False)Transform local coordinate to parent coordinate
Parameters
relative: bool, default to False Change to True is you want to translate relativeposition from widget to his parent.
to_widget(x, y, relative=False)Return the coordinate from window to local widget
to_window(x, y, initial=True, relative=False)Transform local coordinate to window coordinate
topTop position of the widget
top is a AliasProperty of (y + height)
unbind(**kwargs)Unbind properties or event from handler
See bind() for more information.
widthWidth of the widget.
width is a NumericProperty, default to 100.
xX position of the widget.
x is a NumericProperty, default to 0.
yY position of the widget.
y is a NumericProperty, default to 0.
class kivy.uix.widget.WidgetExceptionBases: exceptions.Exception
Fired when the widget got an exception
116
Part III
INDICES AND TABLES
• genindex
• modindex
• search
117
118
PYTHON MODULE INDEX
kkivy, 27kivy.animation, 28kivy.app, 30kivy.base, 32kivy.cache, 32kivy.clock, 34kivy.config, 35kivy.core, 53kivy.core.audio, 53kivy.core.camera, 54kivy.core.clipboard, 55kivy.core.gl, 55kivy.core.image, 55kivy.core.spelling, 56kivy.core.svg, 57kivy.core.text, 58kivy.core.video, 59kivy.core.window, 60kivy.event, 37kivy.factory, 38kivy.gesture, 38kivy.graphics, 63kivy.graphics.compiler, 63kivy.graphics.context_instructions, 64kivy.graphics.fbo, 66kivy.graphics.instructions, 67kivy.graphics.texture, 70kivy.graphics.transformation, 73kivy.graphics.vertex_instructions, 73kivy.input, 77kivy.input.factory, 82kivy.input.motionevent, 83kivy.input.postproc, 77kivy.input.postproc.dejitter, 77kivy.input.postproc.doubletap, 78kivy.input.postproc.ignorelist, 78kivy.input.postproc.retaintouch, 78kivy.input.provider, 87kivy.input.providers, 79kivy.input.providers.hidinput, 79kivy.input.providers.linuxwacom, 79kivy.input.providers.mactouch, 80
kivy.input.providers.mouse, 80kivy.input.providers.mtdev, 80kivy.input.providers.probesysfs, 81kivy.input.providers.tuio, 81kivy.input.providers.wm_common, 82kivy.input.providers.wm_pen, 82kivy.input.providers.wm_touch, 82kivy.input.shape, 87kivy.lang, 40kivy.loader, 44kivy.logger, 45kivy.modules, 89kivy.properties, 45kivy.resources, 48kivy.uix, 91kivy.uix.anchorlayout, 91kivy.uix.boxlayout, 91kivy.uix.button, 92kivy.uix.camera, 93kivy.uix.floatlayout, 94kivy.uix.gridlayout, 95kivy.uix.image, 96kivy.uix.label, 97kivy.uix.layout, 99kivy.uix.scatter, 100kivy.uix.slider, 104kivy.uix.textinput, 105kivy.uix.togglebutton, 110kivy.uix.video, 110kivy.uix.widget, 111kivy.utils, 48kivy.vector, 49kivy.weakmethod, 52
119
120
INDEX
Aadd (kivy.graphics.instructions.Canvas attribute),
69add (kivy.graphics.instructions.InstructionGroup
attribute), 68add_gesture() (kivy.gesture.GestureDatabase
method), 39add_point (kivy.graphics.vertex_instructions.Point
attribute), 75add_point() (kivy.gesture.GestureStroke method),
39add_stroke() (kivy.gesture.Gesture method), 39add_widget() (kivy.core.window.WindowBase
method), 60add_widget() (kivy.uix.widget.Widget method),
112adddefaultsection() (kivy.config.KivyConfigParser
method), 37after (kivy.graphics.instructions.Canvas attribute),
69AliasProperty (class in kivy.properties), 47anchor_x (kivy.uix.anchorlayout.AnchorLayout
attribute), 91anchor_y (kivy.uix.anchorlayout.AnchorLayout
attribute), 91AnchorLayout (class in kivy.uix.anchorlayout), 91angle (kivy.graphics.context_instructions.Rotate
attribute), 65angle() (kivy.vector.Vector method), 50Animation (class in kivy.animation), 29AnimationTransition (class in kivy.animation), 29App (class in kivy.app), 30append() (kivy.cache.Cache static method), 33apply() (kivy.lang.BuilderBase method), 43apply_angle_scale_trans() (kivy.uix.scatter.Scatter
method), 101apply_transform() (kivy.uix.scatter.Scatter
method), 101apply_transform_2d()
(kivy.input.motionevent.MotionEventmethod), 84
ask_update (kivy.graphics.instructions.Callbackattribute), 70
ask_update (kivy.graphics.instructions.Canvas at-tribute), 69
AsyncImage (class in kivy.uix.image), 97auto_bring_to_front (kivy.uix.scatter.Scatter
attribute), 101axis (kivy.graphics.context_instructions.Rotate at-
tribute), 65
Bbbox (kivy.uix.scatter.Scatter attribute), 101before (kivy.graphics.instructions.Canvas at-
tribute), 69bind (kivy.event.EventDispatcher attribute), 37bind (kivy.graphics.fbo.Fbo attribute), 67bind (kivy.graphics.texture.Texture attribute), 71bind (kivy.properties.Property attribute), 47bind() (kivy.uix.widget.Widget method), 112BindTexture (class in
kivy.graphics.context_instructions),65
blit_buffer (kivy.graphics.texture.Texture at-tribute), 71
blit_data (kivy.graphics.texture.Texture attribute),71
bold (kivy.uix.label.Label attribute), 97BooleanProperty (class in kivy.properties), 46border (kivy.graphics.vertex_instructions.BorderImage
attribute), 74BorderImage (class in
kivy.graphics.vertex_instructions), 74boundary() (in module kivy.utils), 49BoundedNumericProperty (class in
kivy.properties), 46BoxLayout (class in kivy.uix.boxlayout), 92build() (kivy.app.App method), 31Builder (in module kivy.lang), 43BuilderBase (class in kivy.lang), 43Button (class in kivy.uix.button), 93
CCache (class in kivy.cache), 33Callback (class in kivy.graphics.instructions), 70Camera (class in kivy.uix.camera), 93CameraBase (class in kivy.core.camera), 54
121
cancel_selection() (kivy.uix.textinput.TextInputmethod), 107
Canvas (class in kivy.graphics.instructions), 69canvas (kivy.uix.widget.Widget attribute), 112center (kivy.core.window.WindowBase attribute),
60center (kivy.uix.scatter.Scatter attribute), 101center (kivy.uix.widget.Widget attribute), 112center_stroke() (kivy.gesture.GestureStroke
method), 39center_x (kivy.uix.widget.Widget attribute), 112center_y (kivy.uix.widget.Widget attribute), 112check() (kivy.core.spelling.SpellingBase method),
56children (kivy.uix.widget.Widget attribute), 113clear (kivy.graphics.instructions.Canvas attribute),
69clear (kivy.graphics.instructions.InstructionGroup
attribute), 68clear() (kivy.core.window.WindowBase method),
60clear_buffer (kivy.graphics.fbo.Fbo attribute), 67clear_color (kivy.graphics.fbo.Fbo attribute), 67clear_widgets() (kivy.uix.widget.Widget method),
113clearcolor (kivy.core.window.WindowBase at-
tribute), 60Clock (in module kivy.clock), 34ClockBase (class in kivy.clock), 34close() (kivy.core.window.WindowBase method),
61cls (kivy.uix.widget.Widget attribute), 113collide_point() (kivy.uix.widget.Widget method),
113collide_widget() (kivy.uix.widget.Widget
method), 113Color (class in kivy.graphics.context_instructions),
64color (kivy.uix.label.Label attribute), 97cols (kivy.uix.gridlayout.GridLayout attribute), 95Config (in module kivy.config), 37content_height (kivy.core.text.LabelBase at-
tribute), 58content_size (kivy.core.text.LabelBase attribute),
58content_width (kivy.core.text.LabelBase attribute),
58ContextInstruction (class in
kivy.graphics.instructions), 68copy_to() (kivy.input.motionevent.MotionEvent
method), 84create() (kivy.graphics.texture.Texture method), 71create() (kivy.input.providers.tuio.TuioMotionEventProvider
static method), 82create_from_data() (kivy.graphics.texture.Texture
method), 71create_property() (kivy.uix.widget.Widget
method), 113create_window() (kivy.core.window.WindowBase
method), 61curry() (in module kivy.utils), 48cursor (kivy.uix.textinput.TextInput attribute), 107cursor_blink (kivy.uix.textinput.TextInput at-
tribute), 107cursor_col (kivy.uix.textinput.TextInput attribute),
107cursor_index() (kivy.uix.textinput.TextInput
method), 107cursor_offset() (kivy.uix.textinput.TextInput
method), 107cursor_pos (kivy.uix.textinput.TextInput at-
tribute), 107cursor_row (kivy.uix.textinput.TextInput at-
tribute), 107
Ddelete_selection() (kivy.uix.textinput.TextInput
method), 107depack() (kivy.input.motionevent.MotionEvent
method), 84deprecated() (in module kivy.utils), 49device (kivy.input.motionevent.MotionEvent at-
tribute), 84difference() (in module kivy.utils), 48disable (kivy.graphics.texture.Texture attribute),
71dispatch (kivy.event.EventDispatcher attribute),
37distance() (kivy.input.motionevent.MotionEvent
method), 84distance() (kivy.vector.Vector method), 50distance2() (kivy.vector.Vector method), 51do_backspace() (kivy.uix.textinput.TextInput
method), 107do_cursor_movement()
(kivy.uix.textinput.TextInput method),108
do_rotation (kivy.uix.scatter.Scatter attribute), 102do_scale (kivy.uix.scatter.Scatter attribute), 102do_translation (kivy.uix.scatter.Scatter attribute),
102do_translation_x (kivy.uix.scatter.Scatter at-
tribute), 102do_translation_y (kivy.uix.scatter.Scatter at-
tribute), 102dot() (kivy.vector.Vector method), 51dot_product() (kivy.gesture.Gesture method), 39double_tap_time (kivy.input.motionevent.MotionEvent
attribute), 84dpos (kivy.input.motionevent.MotionEvent at-
tribute), 84
122
draw (kivy.graphics.instructions.Canvas at-tribute), 69
dsx (kivy.input.motionevent.MotionEvent at-tribute), 84
dsy (kivy.input.motionevent.MotionEvent at-tribute), 84
dsz (kivy.input.motionevent.MotionEvent at-tribute), 84
duration (kivy.animation.Animation attribute), 29duration (kivy.core.video.VideoBase attribute), 59duration (kivy.uix.video.Video attribute), 110dx (kivy.input.motionevent.MotionEvent at-
tribute), 84dy (kivy.input.motionevent.MotionEvent at-
tribute), 84dz (kivy.input.motionevent.MotionEvent at-
tribute), 85
EEllipse (class in kivy.graphics.vertex_instructions),
74enable (kivy.graphics.texture.Texture attribute), 71eos (kivy.uix.video.Video attribute), 111error_image (kivy.loader.LoaderBase attribute), 44EventDispatcher (class in kivy.event), 37EventLoop (in module kivy.base), 32ExceptionHandler (class in kivy.base), 32ExceptionManager (in module kivy.base), 32
FFactory (in module kivy.factory), 38Fbo (class in kivy.graphics.fbo), 67filename (kivy.core.audio.Sound attribute), 53filename (kivy.core.image.Image attribute), 55filename (kivy.core.svg.Svg attribute), 57filename (kivy.core.video.VideoBase attribute), 59find() (kivy.gesture.GestureDatabase method), 39find_double_tap() (kivy.input.postproc.doubletap.InputPostprocDoubleTap
method), 78flip() (kivy.core.window.WindowBase method), 61flip_vertical (kivy.graphics.texture.Texture at-
tribute), 71FloatLayout (class in kivy.uix.floatlayout), 94focus (kivy.uix.textinput.TextInput attribute), 108font_name (kivy.uix.label.Label attribute), 97font_name (kivy.uix.textinput.TextInput at-
tribute), 108font_size (kivy.uix.label.Label attribute), 97font_size (kivy.uix.textinput.TextInput attribute),
108fontid (kivy.core.text.LabelBase attribute), 58frametime (kivy.clock.ClockBase attribute), 34
GGesture (class in kivy.gesture), 39
gesture_to_str() (kivy.gesture.GestureDatabasemethod), 39
GestureDatabase (class in kivy.gesture), 39GestureStroke (class in kivy.gesture), 39get (kivy.properties.Property attribute), 47get() (kivy.cache.Cache static method), 33get() (kivy.input.factory.MotionEventFactory
static method), 83get_boottime() (kivy.clock.ClockBase method), 34get_color_from_hex() (in module kivy.utils), 48get_cursor_from_index()
(kivy.uix.textinput.TextInput method),108
get_cursor_from_xy()(kivy.uix.textinput.TextInput method),108
get_extents() (kivy.core.text.LabelBase method), 58get_fps() (kivy.clock.ClockBase method), 34get_group (kivy.graphics.instructions.InstructionGroup
attribute), 68get_lastaccess() (kivy.cache.Cache static method),
33get_parent_window() (kivy.uix.widget.Widget
method), 114get_random_color() (in module kivy.utils), 48get_region (kivy.graphics.texture.Texture at-
tribute), 71get_rfps() (kivy.clock.ClockBase method), 34get_rigid_rotation() (kivy.gesture.Gesture
method), 39get_root_window() (kivy.uix.widget.Widget
method), 114get_score() (kivy.gesture.Gesture method), 39get_time() (kivy.clock.ClockBase method), 34get_timestamp() (kivy.cache.Cache static method),
33getdefault() (kivy.config.KivyConfigParser
method), 37getter() (kivy.uix.widget.Widget method), 114gl_init_resources() (in module
kivy.graphics.context_instructions),66
grab() (kivy.input.motionevent.MotionEventmethod), 85
grab_current (kivy.input.motionevent.MotionEventattribute), 85
GridLayout (class in kivy.uix.gridlayout), 95GridLayoutException (class in
kivy.uix.gridlayout), 95group (kivy.uix.togglebutton.ToggleButton at-
tribute), 110
Hhalign (kivy.uix.label.Label attribute), 98handle_exception() (kivy.base.ExceptionHandler
method), 32
123
height (kivy.core.image.Image attribute), 55height (kivy.core.window.WindowBase attribute),
61height (kivy.graphics.texture.Texture attribute), 71height (kivy.uix.widget.Widget attribute), 114
Iid (kivy.graphics.texture.Texture attribute), 71id (kivy.input.motionevent.MotionEvent at-
tribute), 85id (kivy.uix.widget.Widget attribute), 114identity (kivy.graphics.transformation.Matrix at-
tribute), 73Image (class in kivy.core.image), 55Image (class in kivy.uix.image), 96image (kivy.core.image.Image attribute), 55image() (kivy.loader.LoaderBase method), 44image_ratio (kivy.uix.image.Image attribute), 96ImageData (class in kivy.core.image), 56in_bbox() (kivy.vector.Vector static method), 51index (kivy.core.camera.CameraBase attribute), 54index (kivy.uix.camera.Camera attribute), 93init_camera() (kivy.core.camera.CameraBase
method), 54InputPostprocDejitter (class in
kivy.input.postproc.dejitter), 77InputPostprocDoubleTap (class in
kivy.input.postproc.doubletap), 78InputPostprocIgnoreList (class in
kivy.input.postproc.ignorelist), 78InputPostprocRetainTouch (class in
kivy.input.postproc.retaintouch), 78insert (kivy.graphics.instructions.InstructionGroup
attribute), 68insert_text() (kivy.uix.textinput.TextInput
method), 108Instruction (class in kivy.graphics.instructions), 67InstructionGroup (class in
kivy.graphics.instructions), 68interpolate() (in module kivy.utils), 49intersection() (in module kivy.utils), 48inverse (kivy.graphics.transformation.Matrix at-
tribute), 73is_color_transparent() (in module kivy.utils), 48is_dead() (kivy.weakmethod.WeakMethod
method), 52is_double_tap (kivy.input.motionevent.MotionEvent
attribute), 85is_touch (kivy.input.motionevent.MotionEvent at-
tribute), 85italic (kivy.uix.label.Label attribute), 98
Kkivy (module), 27kivy.animation (module), 28
kivy.app (module), 30kivy.base (module), 32kivy.cache (module), 32kivy.clock (module), 34kivy.config (module), 35kivy.core (module), 53kivy.core.audio (module), 53kivy.core.camera (module), 54kivy.core.clipboard (module), 55kivy.core.gl (module), 55kivy.core.image (module), 55kivy.core.spelling (module), 56kivy.core.svg (module), 57kivy.core.text (module), 58kivy.core.video (module), 59kivy.core.window (module), 60kivy.event (module), 37kivy.factory (module), 38kivy.gesture (module), 38kivy.graphics (module), 63kivy.graphics.compiler (module), 63kivy.graphics.context_instructions (module), 64kivy.graphics.fbo (module), 66kivy.graphics.instructions (module), 67kivy.graphics.texture (module), 70kivy.graphics.transformation (module), 73kivy.graphics.vertex_instructions (module), 73kivy.input (module), 77kivy.input.factory (module), 82kivy.input.motionevent (module), 83kivy.input.postproc (module), 77kivy.input.postproc.dejitter (module), 77kivy.input.postproc.doubletap (module), 78kivy.input.postproc.ignorelist (module), 78kivy.input.postproc.retaintouch (module), 78kivy.input.provider (module), 87kivy.input.providers (module), 79kivy.input.providers.hidinput (module), 79kivy.input.providers.linuxwacom (module), 79kivy.input.providers.mactouch (module), 80kivy.input.providers.mouse (module), 80kivy.input.providers.mtdev (module), 80kivy.input.providers.probesysfs (module), 81kivy.input.providers.tuio (module), 81kivy.input.providers.wm_common (module), 82kivy.input.providers.wm_pen (module), 82kivy.input.providers.wm_touch (module), 82kivy.input.shape (module), 87kivy.lang (module), 40kivy.loader (module), 44kivy.logger (module), 45kivy.modules (module), 89kivy.properties (module), 45kivy.resources (module), 48kivy.uix (module), 91
124
kivy.uix.anchorlayout (module), 91kivy.uix.boxlayout (module), 91kivy.uix.button (module), 92kivy.uix.camera (module), 93kivy.uix.floatlayout (module), 94kivy.uix.gridlayout (module), 95kivy.uix.image (module), 96kivy.uix.label (module), 97kivy.uix.layout (module), 99kivy.uix.scatter (module), 100kivy.uix.slider (module), 104kivy.uix.textinput (module), 105kivy.uix.togglebutton (module), 110kivy.uix.video (module), 110kivy.uix.widget (module), 111kivy.utils (module), 48kivy.vector (module), 49kivy.weakmethod (module), 52kivy_base_dir (in module kivy), 28kivy_config_fn (in module kivy), 28kivy_configure() (in module kivy), 27kivy_data_dir (in module kivy), 28kivy_home_dir (in module kivy), 28kivy_icons_dir (in module kivy), 28kivy_libs_dir (in module kivy), 28kivy_modules_dir (in module kivy), 28kivy_options (in module kivy), 28kivy_providers_dir (in module kivy), 28kivy_register_post_configuration() (in module
kivy), 27kivy_shader_dir (in module kivy), 28kivy_usermodules_dir (in module kivy), 28KivyConfigParser (class in kivy.config), 37
LLabel (class in kivy.uix.label), 97label (kivy.core.text.LabelBase attribute), 58LabelBase (class in kivy.core.text), 58Layout (class in kivy.uix.layout), 100length (kivy.core.audio.Sound attribute), 53length() (kivy.vector.Vector method), 51length2() (kivy.vector.Vector method), 51Line (class in kivy.graphics.vertex_instructions),
74line_height (kivy.uix.textinput.TextInput at-
tribute), 108line_intersection() (kivy.vector.Vector static
method), 51LineWidth (class in
kivy.graphics.context_instructions),64
link (kivy.properties.Property attribute), 47list() (kivy.input.factory.MotionEventFactory static
method), 83
list_languages() (kivy.core.spelling.SpellingBasemethod), 57
ListProperty (class in kivy.properties), 46load() (kivy.core.audio.Sound method), 53load() (kivy.core.audio.SoundLoader static
method), 54load() (kivy.core.image.Image static method), 56load() (kivy.core.svg.Svg static method), 57load() (kivy.core.video.VideoBase method), 59load_file() (kivy.lang.BuilderBase method), 43load_kv() (kivy.app.App method), 31load_resource() (kivy.lang.Parser method), 43load_string() (kivy.lang.BuilderBase method), 43LoaderBase (class in kivy.loader), 44loading_image (kivy.loader.LoaderBase attribute),
44Logger (in module kivy.logger), 45LoggerHistory (in module kivy.logger), 45
Mmag_filter (kivy.graphics.texture.Texture at-
tribute), 71match() (kivy.lang.BuilderBase method), 43Matrix (class in kivy.graphics.transformation), 73matrix (kivy.graphics.context_instructions.MatrixInstruction
attribute), 66MatrixInstruction (class in
kivy.graphics.context_instructions),66
max (kivy.uix.slider.Slider attribute), 104min (kivy.uix.slider.Slider attribute), 104min_filter (kivy.graphics.texture.Texture at-
tribute), 72minimum_size (kivy.uix.layout.Layout attribute),
100mipmap (kivy.graphics.texture.Texture attribute),
72MotionEvent (class in kivy.input.motionevent), 84MotionEventFactory (class in kivy.input.factory),
82MotionEventProvider (class in
kivy.input.provider), 87move() (kivy.input.motionevent.MotionEvent
method), 85multiline (kivy.uix.textinput.TextInput attribute),
108multiply (kivy.graphics.transformation.Matrix at-
tribute), 73
NNoLanguageSelectedError (class in
kivy.core.spelling), 57norm_image_size (kivy.uix.image.Image at-
tribute), 96normalize() (kivy.gesture.Gesture method), 39
125
normalize() (kivy.vector.Vector method), 52normalize_stroke() (kivy.gesture.GestureStroke
method), 40NoSuchLangError (class in kivy.core.spelling), 57NumericProperty (class in kivy.properties), 45, 47
OObjectProperty (class in kivy.properties), 46on_close() (kivy.core.window.WindowBase
method), 61on_flip() (kivy.core.window.WindowBase
method), 61on_key_down() (kivy.core.window.WindowBase
method), 61on_key_up() (kivy.core.window.WindowBase
method), 61on_keyboard() (kivy.core.window.WindowBase
method), 61on_motion() (kivy.core.window.WindowBase
method), 61on_mouse_down() (kivy.core.window.WindowBase
method), 61on_mouse_move() (kivy.core.window.WindowBase
method), 61on_mouse_up() (kivy.core.window.WindowBase
method), 61on_resize() (kivy.core.window.WindowBase
method), 62on_rotate() (kivy.core.window.WindowBase
method), 62on_start() (kivy.app.App method), 31on_stop() (kivy.app.App method), 31on_touch_down() (kivy.core.window.WindowBase
method), 62on_touch_down() (kivy.uix.widget.Widget
method), 114on_touch_move() (kivy.core.window.WindowBase
method), 62on_touch_move() (kivy.uix.widget.Widget
method), 114on_touch_up() (kivy.core.window.WindowBase
method), 62on_touch_up() (kivy.uix.widget.Widget method),
114opos (kivy.input.motionevent.MotionEvent at-
tribute), 85OptionProperty (class in kivy.properties), 46orientation (kivy.uix.boxlayout.BoxLayout at-
tribute), 92orientation (kivy.uix.slider.Slider attribute), 104osx (kivy.input.motionevent.MotionEvent at-
tribute), 85osy (kivy.input.motionevent.MotionEvent at-
tribute), 85
osz (kivy.input.motionevent.MotionEvent at-tribute), 85
ox (kivy.input.motionevent.MotionEvent at-tribute), 85
oy (kivy.input.motionevent.MotionEvent at-tribute), 85
oz (kivy.input.motionevent.MotionEvent at-tribute), 85
Ppadding (kivy.uix.anchorlayout.AnchorLayout at-
tribute), 91padding (kivy.uix.boxlayout.BoxLayout attribute),
92padding (kivy.uix.gridlayout.GridLayout at-
tribute), 95padding (kivy.uix.label.Label attribute), 98padding (kivy.uix.slider.Slider attribute), 104padding (kivy.uix.textinput.TextInput attribute),
109padding_x (kivy.uix.label.Label attribute), 98padding_x (kivy.uix.textinput.TextInput at-
tribute), 109padding_y (kivy.uix.label.Label attribute), 98padding_y (kivy.uix.textinput.TextInput at-
tribute), 109parent (kivy.uix.widget.Widget attribute), 114parse() (kivy.lang.Parser method), 43parse_level() (kivy.lang.Parser method), 44parse_version() (kivy.lang.Parser method), 44Parser (class in kivy.lang), 43play (kivy.uix.camera.Camera attribute), 93play (kivy.uix.video.Video attribute), 111play() (kivy.core.audio.Sound method), 53play() (kivy.core.video.VideoBase method), 59Point (class in kivy.graphics.vertex_instructions),
75points (kivy.graphics.vertex_instructions.Line at-
tribute), 74points (kivy.graphics.vertex_instructions.Point at-
tribute), 75points (kivy.graphics.vertex_instructions.Quad at-
tribute), 74points (kivy.graphics.vertex_instructions.Triangle
attribute), 73points_distance() (kivy.gesture.GestureStroke
method), 40pointsize (kivy.graphics.vertex_instructions.Point
attribute), 75pop() (kivy.input.motionevent.MotionEvent
method), 85PopMatrix (class in
kivy.graphics.context_instructions),65
pos (kivy.graphics.vertex_instructions.Rectangleattribute), 74
126
pos (kivy.input.motionevent.MotionEvent at-tribute), 86
pos (kivy.uix.scatter.Scatter attribute), 102pos (kivy.uix.widget.Widget attribute), 114pos_hint (kivy.uix.widget.Widget attribute), 114position (kivy.core.video.VideoBase attribute), 59position (kivy.uix.video.Video attribute), 111ppos (kivy.input.motionevent.MotionEvent at-
tribute), 86print_usage() (kivy.cache.Cache static method), 33profile (kivy.input.motionevent.MotionEvent at-
tribute), 86properties (kivy.animation.Animation attribute),
29Property (class in kivy.properties), 47ProxyImage (class in kivy.loader), 44psx (kivy.input.motionevent.MotionEvent at-
tribute), 86psy (kivy.input.motionevent.MotionEvent at-
tribute), 86psz (kivy.input.motionevent.MotionEvent at-
tribute), 86push() (kivy.input.motionevent.MotionEvent
method), 86push_attrs_stack (kivy.input.motionevent.MotionEvent
attribute), 86PushMatrix (class in
kivy.graphics.context_instructions),65
px (kivy.input.motionevent.MotionEvent at-tribute), 86
py (kivy.input.motionevent.MotionEvent at-tribute), 86
pz (kivy.input.motionevent.MotionEvent at-tribute), 86
QQuad (class in kivy.graphics.vertex_instructions),
74
Rrange (kivy.uix.slider.Slider attribute), 104read_pixel() (kivy.core.image.Image method), 56Rectangle (class in
kivy.graphics.vertex_instructions), 74rectangle (kivy.graphics.texture.Texture attribute),
72ReferenceListProperty (class in kivy.properties), 46refresh() (kivy.core.text.LabelBase method), 58register() (kivy.cache.Cache static method), 33register() (kivy.core.audio.SoundLoader static
method), 54register() (kivy.input.factory.MotionEventFactory
static method), 83register() (kivy.input.providers.tuio.TuioMotionEventProvider
static method), 82
register_event_type (kivy.event.EventDispatcherattribute), 37
release (kivy.graphics.fbo.Fbo attribute), 67release_keyboard() (kivy.core.window.WindowBase
method), 62remove (kivy.graphics.instructions.Canvas at-
tribute), 69remove (kivy.graphics.instructions.InstructionGroup
attribute), 68remove() (kivy.cache.Cache static method), 34remove_group (kivy.graphics.instructions.InstructionGroup
attribute), 68remove_widget() (kivy.core.window.WindowBase
method), 62remove_widget() (kivy.uix.widget.Widget
method), 115render() (kivy.core.text.LabelBase method), 58RenderContext (class in
kivy.graphics.instructions), 69reposition_child() (kivy.uix.layout.Layout
method), 100request_keyboard() (kivy.core.window.WindowBase
method), 62require() (in module kivy), 27reset_context (kivy.graphics.instructions.Callback
attribute), 70resolution (kivy.core.camera.CameraBase at-
tribute), 54resolution (kivy.uix.camera.Camera attribute), 94resource_add_path() (in module kivy.resources),
48resource_find() (in module kivy.resources), 48right (kivy.uix.widget.Widget attribute), 115root (kivy.app.App attribute), 31Rotate (class in kivy.graphics.context_instructions),
65rotate (kivy.graphics.transformation.Matrix at-
tribute), 73rotate() (kivy.vector.Vector method), 52rotation (kivy.uix.scatter.Scatter attribute), 102rows (kivy.uix.gridlayout.GridLayout attribute),
95run() (kivy.app.App method), 31run() (kivy.loader.LoaderBase method), 44runTouchApp() (in module kivy.base), 32
SSafeList (class in kivy.utils), 49Scale (class in kivy.graphics.context_instructions),
65scale (kivy.graphics.context_instructions.Scale at-
tribute), 65scale (kivy.graphics.transformation.Matrix at-
tribute), 73scale (kivy.uix.scatter.Scatter attribute), 102
127
scale_for_screen() (kivy.input.motionevent.MotionEventmethod), 86
scale_max (kivy.uix.scatter.Scatter attribute), 103scale_min (kivy.uix.scatter.Scatter attribute), 103scale_stroke() (kivy.gesture.GestureStroke
method), 40Scatter (class in kivy.uix.scatter), 101schedule_interval() (kivy.clock.ClockBase
method), 34schedule_once() (kivy.clock.ClockBase method),
35screenshot() (kivy.core.window.WindowBase
method), 62scroll_x (kivy.uix.textinput.TextInput attribute),
109scroll_y (kivy.uix.textinput.TextInput attribute),
109seek() (kivy.core.audio.Sound method), 53seek() (kivy.core.video.VideoBase method), 59segments (kivy.graphics.vertex_instructions.Ellipse
attribute), 74select_language() (kivy.core.spelling.SpellingBase
method), 57selection_color (kivy.uix.textinput.TextInput at-
tribute), 109selection_from (kivy.uix.textinput.TextInput at-
tribute), 109selection_text (kivy.uix.textinput.TextInput at-
tribute), 109selection_to (kivy.uix.textinput.TextInput at-
tribute), 109set (kivy.graphics.context_instructions.Rotate at-
tribute), 65set (kivy.properties.Property attribute), 48set_translate (kivy.graphics.context_instructions.Translate
attribute), 65setdefault() (kivy.config.KivyConfigParser
method), 37setter() (kivy.uix.widget.Widget method), 115Shape (class in kivy.input.shape), 87shape (kivy.input.motionevent.MotionEvent at-
tribute), 86ShapeRect (class in kivy.input.shape), 87size (kivy.core.image.Image attribute), 56size (kivy.core.window.WindowBase attribute), 62size (kivy.graphics.fbo.Fbo attribute), 67size (kivy.graphics.vertex_instructions.Rectangle
attribute), 74size (kivy.uix.widget.Widget attribute), 115size_hint (kivy.uix.widget.Widget attribute), 115size_hint_x (kivy.uix.widget.Widget attribute), 115size_hint_y (kivy.uix.widget.Widget attribute),
115Slider (class in kivy.uix.slider), 104Sound (class in kivy.core.audio), 53
SoundLoader (class in kivy.core.audio), 54source (kivy.graphics.context_instructions.BindTexture
attribute), 65source (kivy.graphics.instructions.VertexInstruction
attribute), 68source (kivy.uix.image.Image attribute), 96spacing (kivy.uix.boxlayout.BoxLayout attribute),
92spacing (kivy.uix.gridlayout.GridLayout at-
tribute), 95SpellingBase (class in kivy.core.spelling), 56spos (kivy.input.motionevent.MotionEvent at-
tribute), 86start() (kivy.animation.Animation method), 29start() (kivy.core.camera.CameraBase method), 55start() (kivy.input.provider.MotionEventProvider
method), 87start() (kivy.input.providers.tuio.TuioMotionEventProvider
method), 82start() (kivy.loader.LoaderBase method), 44state (kivy.core.video.VideoBase attribute), 59state (kivy.uix.button.Button attribute), 93status (kivy.core.audio.Sound attribute), 53stop() (kivy.animation.Animation method), 29stop() (kivy.app.App method), 31stop() (kivy.core.audio.Sound method), 54stop() (kivy.core.camera.CameraBase method), 55stop() (kivy.core.video.VideoBase method), 59stop() (kivy.input.provider.MotionEventProvider
method), 87stop() (kivy.input.providers.tuio.TuioMotionEventProvider
method), 82stop() (kivy.loader.LoaderBase method), 44stop_all() (kivy.animation.Animation static
method), 29stop_property() (kivy.animation.Animation
method), 29stopTouchApp() (in module kivy.base), 32str_to_gesture() (kivy.gesture.GestureDatabase
method), 39StringProperty (class in kivy.properties), 46strip_comments() (kivy.lang.Parser method), 44stroke_length() (kivy.gesture.GestureStroke
method), 40strtotuple() (in module kivy.utils), 48suggest() (kivy.core.spelling.SpellingBase
method), 57Svg (class in kivy.core.svg), 57sx (kivy.input.motionevent.MotionEvent at-
tribute), 86sy (kivy.input.motionevent.MotionEvent at-
tribute), 86system_size (kivy.core.window.WindowBase at-
tribute), 62sz (kivy.input.motionevent.MotionEvent at-
128
tribute), 86
Ttab_width (kivy.uix.textinput.TextInput attribute),
109target (kivy.graphics.texture.Texture attribute), 72tex_coords (kivy.graphics.instructions.VertexInstruction
attribute), 68tex_coords (kivy.graphics.texture.Texture at-
tribute), 72text (kivy.core.text.LabelBase attribute), 58text (kivy.uix.label.Label attribute), 98text (kivy.uix.textinput.TextInput attribute), 109text_size (kivy.uix.label.Label attribute), 98TextInput (class in kivy.uix.textinput), 107Texture (class in kivy.graphics.texture), 70texture (kivy.core.camera.CameraBase attribute),
55texture (kivy.core.image.Image attribute), 56texture (kivy.core.video.VideoBase attribute), 59texture (kivy.graphics.fbo.Fbo attribute), 67texture (kivy.graphics.instructions.VertexInstruction
attribute), 69texture (kivy.uix.image.Image attribute), 97texture (kivy.uix.label.Label attribute), 98texture_size (kivy.uix.image.Image attribute), 97texture_size (kivy.uix.label.Label attribute), 99texture_update() (kivy.uix.label.Label method), 99TextureRegion (class in kivy.graphics.texture), 72tick() (kivy.clock.ClockBase method), 35tick_draw() (kivy.clock.ClockBase method), 35time_start (kivy.input.motionevent.MotionEvent
attribute), 86to_local() (kivy.uix.widget.Widget method), 115to_parent() (kivy.uix.widget.Widget method), 116to_widget() (kivy.uix.widget.Widget method), 116to_window() (kivy.uix.widget.Widget method),
116toggle_fullscreen() (kivy.core.window.WindowBase
method), 62ToggleButton (class in kivy.uix.togglebutton), 110top (kivy.uix.widget.Widget attribute), 116transform (kivy.uix.scatter.Scatter attribute), 103transform_inv (kivy.uix.scatter.Scatter attribute),
103transform_point (kivy.graphics.transformation.Matrix
attribute), 73transition (kivy.animation.Animation attribute),
29Translate (class in
kivy.graphics.context_instructions),65
translate (kivy.graphics.transformation.Matrix at-tribute), 73
Triangle (class in kivy.graphics.vertex_instructions),73
Tuio2dCurMotionEvent (class inkivy.input.providers.tuio), 82
Tuio2dObjMotionEvent (class inkivy.input.providers.tuio), 82
TuioMotionEventProvider (class inkivy.input.providers.tuio), 81
Uud (kivy.input.motionevent.MotionEvent at-
tribute), 86uid (kivy.input.motionevent.MotionEvent at-
tribute), 86unbind (kivy.event.EventDispatcher attribute), 38unbind (kivy.properties.Property attribute), 48unbind() (kivy.uix.widget.Widget method), 116ungrab() (kivy.input.motionevent.MotionEvent
method), 86uniform_height (kivy.uix.gridlayout.GridLayout
attribute), 95uniform_width (kivy.uix.gridlayout.GridLayout
attribute), 95unlink (kivy.properties.Property attribute), 48unload() (kivy.core.audio.Sound method), 54unload() (kivy.core.video.VideoBase method), 59unregister() (kivy.input.providers.tuio.TuioMotionEventProvider
static method), 82unregister_event_types
(kivy.event.EventDispatcher attribute),38
unschedule() (kivy.clock.ClockBase method), 35update() (kivy.input.provider.MotionEventProvider
method), 87update() (kivy.input.providers.tuio.TuioMotionEventProvider
method), 82update_minimum_size()
(kivy.uix.boxlayout.BoxLayout method),92
update_minimum_size()(kivy.uix.floatlayout.FloatLayoutmethod), 94
uvpos (kivy.graphics.texture.Texture attribute), 72uvsize (kivy.graphics.texture.Texture attribute), 72
Vvalign (kivy.uix.label.Label attribute), 99value (kivy.uix.slider.Slider attribute), 104value_normalized (kivy.uix.slider.Slider attribute),
105value_pos (kivy.uix.slider.Slider attribute), 105Vector (class in kivy.vector), 50VertexInstruction (class in
kivy.graphics.instructions), 68Video (class in kivy.uix.video), 110VideoBase (class in kivy.core.video), 59view_clip (kivy.graphics.transformation.Matrix
attribute), 73
129
volume (kivy.core.audio.Sound attribute), 54volume (kivy.core.video.VideoBase attribute), 59volume (kivy.uix.video.Video attribute), 111
WWeakMethod (class in kivy.weakmethod), 52Widget (class in kivy.uix.widget), 112WidgetException (class in kivy.uix.widget), 116width (kivy.core.image.Image attribute), 56width (kivy.core.window.WindowBase attribute),
62width (kivy.graphics.texture.Texture attribute), 72width (kivy.uix.widget.Widget attribute), 116Window (in module kivy.core.window), 62WindowBase (class in kivy.core.window), 60WM_MotionEvent (class in
kivy.input.providers.wm_touch), 82WM_Pen (class in kivy.input.providers.wm_pen),
82wrap (kivy.graphics.texture.Texture attribute), 72write() (kivy.config.KivyConfigParser method), 37
Xx (kivy.graphics.context_instructions.Translate at-
tribute), 65x (kivy.input.motionevent.MotionEvent attribute),
86x (kivy.uix.scatter.Scatter attribute), 103x (kivy.uix.widget.Widget attribute), 116x (kivy.vector.Vector attribute), 52xy (kivy.graphics.context_instructions.Translate
attribute), 65xyz (kivy.graphics.context_instructions.Translate
attribute), 66
Yy (kivy.graphics.context_instructions.Translate at-
tribute), 66y (kivy.input.motionevent.MotionEvent attribute),
87y (kivy.uix.scatter.Scatter attribute), 103y (kivy.uix.widget.Widget attribute), 116y (kivy.vector.Vector attribute), 52
Zz (kivy.graphics.context_instructions.Translate at-
tribute), 66z (kivy.input.motionevent.MotionEvent attribute),
87
130