Kivy Documentation

Transcription

Kivy DocumentationRelease 2.2.0.dev0The Kivy DevelopersMarch 29, 2022

CONTENTSIGetting Started31Introduction52Installing Kivy73A first App154Properties175Kv Design Language196Events217Non-widget stuff238Layouts259Drawing2710 Packaging2911 Diving in31II33Kivy Project12 Philosophy3513 Contributing3714 FAQ5315 Contact Us59III61Programming Guide16 Kivy Basics6317 Controlling the environment6918 Configure Kivy7319 Architectural Overview75i

20 Events and Properties7921 Input management8922 Widgets9723 Graphics11724 Kv language11925 Integrating with other Frameworks13126 Packaging your application13527 Package licensing153IVTutorials15728 Pong Game Tutorial15929 A Simple Paint App17330 Crash Course183VAPI Reference18531 Kivy framework18732 Core Abstraction29933 Kivy module for binary dependencies.33934 Effects34135 Event Manager34736 Garden35137 Graphics35538 Input management43539 Kivy Language46140 External libraries48341 Modules48742 Network support49943 Storage50344 Tools50945 Widgets511ii

VIAppendix77146 License773Python Module Index775Index777iii

iv

Welcome to Kivy’s documentation. Kivy is an open source software library for the rapid developmentof applications equipped with novel user interfaces, such as multi-touch apps.We recommend that you get started with Getting Started. Then head over to the Programming Guide. Wealso have Create an application if you are impatient.You are probably wondering why you should be interested in using Kivy. There is a document outliningour Philosophy that we encourage you to read, and a 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 IGETTING STARTED3

4

CHAPTERONEINTRODUCTIONStart Developing Kivy Apps Right Away!Creating Kivy apps is fun and rewarding. This guide should be the perfect starting point to get youon the right track for app development. You will require a basic knowledge of Python to follow thisintroduction.If you need more background on the Python language, you might be interested in these tutorials: The Official Python Tutorial Learn Python in 10 minutes Learn Python the hard wayWith Kivy, you can create apps that run on: Desktop computers: macOS, Linux, Windows. iOS devices: iPad, iPhone. Android devices: tablets, phones. Any other touch-enabled professional/homebrew devices supporting TUIO (Tangible User Interface Objects).Kivy empowers you with the freedom to write your code once and have it run as-is on different platforms.Follow this guide to get the tools you need, understand the major concepts and learn best practices. Asthis is an introduction, pointers to more information will be provided at the end of each section.As you proceed through the guide, you will, using Kivy: Learn: The basics of programming with the Kivy language.5

Explore: The Kivy framework. Create: A simple cross-platform app. Package: For your choice of platform.Finally, you will learn how to Deploy on the device of your choice.Each section of the guide introduces a new topic, trying to give you enough information to get startedand links to related articles for more in-depth explanations. When you are done with this guide, you’llbe able to develop Kivy apps and you will know where to look for information for the more challengingstuff your innovative applications will require.Enough introductions, let’s get down to business.6

CHAPTERTWOINSTALLING KIVYInstallation for Kivy version 2.2.0.dev0. Read the changelog here. For other Kivy versions, select thedocumentation from the dropdown on the top left.Kivy 2.2.0.dev0 officially supports Python versions 3.7 - allermacOSpip, Kivy.appKivy.app, PyInstallerLinuxpip, spython-for-androidkivy-iosAnacondaconda—2.1 Using pipThe easiest way to install Kivy is with pip, which installs Kivy using either a pre-compiled wheel, ifavailable, otherwise from source (see below).Kivy provides pre-compiled wheels for the supported Python versions on Windows, macOS, Linux, andRPi. Alternatively, installing from source is required for newer Python versions not listed above or if thewheels do not work or fail to run properly.2.1.1 Setup terminal and pipBefore Kivy can be installed, Python and pip needs to be pre-installed. Then, start a new terminal thathas Python available. In the terminal, update pip and other installation dependencies so you have thelatest version as follows (for linux users you may have to substitute python3 instead of python andalso add a --user flag in the subsequent commands outside the virtual environment):python -m pip install --upgrade pip setuptools virtualenv7

2.1.2 Create virtual environmentCreate a new virtual environment for your Kivy project. A virtual environment will prevent possible installation conflicts with other Python versions and packages. It’s optional but strongly recommended:1. Create the virtual environment named kivy venv in your current directory:python -m virtualenv kivy venv2. Activate the virtual environment. You will have to do this step from the current directory everytime you start a new terminal. This sets up the environment so the new kivy venv Python isused.For Windows default CMD, in the command line do:kivy venv\Scripts\activateIf you are in a bash terminal on Windows, instead do:source kivy venv/Scripts/activateIf you are in linux or macOS, instead do:source kivy venv/bin/activateYour terminal should now preface the path with something like (kivy venv), indicating that thekivy venv environment is active. If it doesn’t say that, the virtual environment is not active and thefollowing won’t work.2.1.3 Install KivyFinally, install Kivy using one of the following options:Pre-compiled wheelsThe simplest is to install the current stable version of kivy and optionally kivy examples from thekivy-team provided PyPi wheels. Simply do:python -m pip install "kivy[base]" kivy examplesThis also installs the minimum dependencies of Kivy. To additionally install Kivy with audio/videosupport, install either kivy[base,media] or kivy[full]. See Kivy’s dependencies for the list ofselectors.For the Raspberry Pi, you must additionally install the dependencies listed in source dependenciesbefore installing Kivy above.8

From sourceIf a wheel is not available or is not working, Kivy can be installed from source with some additionalsteps. Installing from source means that Kivy will be installed from source code and compiled directlyon your system.First install the additional system dependencies listed for each platform: Windows, macOS, Linux, RPi.With the dependencies installed, you can now install Kivy into the virtual environment.To install the stable version of Kivy, from the terminal do:python -m pip install "kivy[base]" kivy examples --no-binary kivyTo install the latest cutting-edge Kivy from master, instead do:python -m pip install "kivy[base] @ https://github.com/kivy/kivy/archive/, master.zip"If you want to install Kivy from a different branch, from your forked repository, or from a specificcommit (e.g. to test a fix from a user’s PR) replace the corresponding components of the url.For example to install from the stable branch, the url becomes https://github.com/kivy/kivy/archive/stable.zip. Or to try a specific commit hash, use e.g. ef3f4758aea548da199e10eb382.zipPre-release, pre-compiled wheelsTo install a pre-compiled wheel of the last pre-release version of Kivy, instead of the current stableversion, add the --pre flag to pip:python -m pip install --pre "kivy[base]" kivy examplesThis will only install a development version of Kivy if one was released to PyPi. Instead, one can alsoinstall the latest cutting-edge Nightly wheels from the Kivy server with:python -m pip install kivy --pre --no-deps --index-url https://kivy.org/, downloads/simple/python -m pip install "kivy[base]" --pre --extra-index-url https://kivy., org/downloads/simple/It is done in two steps, because otherwise pip may ignore the wheels on the server and install an olderpre-release version from PyPi.For the Raspberry Pi, remember to additionally install the dependencies listed in source dependenciesbefore installing Kivy above.Development installIf you want to edit Kivy before installing it, or if you want to try fixing some Kivy issue and submita pull request with the fix, you will need to first download the Kivy source code. The following stepsassumes git is pre-installed and available in the terminal.The typical process is to clone Kivy locally with:git clone git://github.com/kivy/kivy.git9

This creates a kivy named folder in your current path. Next, install the additional system dependencieslisted for each OS: Windows, macOS, Linux, RPi.Then change to the kivy directory and install Kivy as an editable install:cd kivypython -m pip install -e ".[dev,full]"Now, you can use git to change branches, edit the code and submit a PR. Remember to compile Kivyeach time you change cython files as follows:python setup.py build ext --inplaceOr if using bash or on Linux, simply do:maketo recompile.To run the test suite, simply run:pytest kivy/testsor in bash or Linux:make test2.1.4 Checking the demoKivy should now be installed. You should be able to import kivy in Python or, if you installed theKivy examples, run the demo.on Windows:python kivy venv\share\kivy-examples\demo\showcase\main.pyor in bash, Linux and macOS:python kivy venv/share/kivy-examples/demo/showcase/main.pyThe exact path to the Kivy examples directory is also stored in kivy.kivy examples dir.The 3d monkey demo under kivy-examples/3Drendering/main.py is also fun to see.2.2 Installation using CondaIf you use Anaconda, you can install Kivy with its package manager Conda using:conda install kivy -c conda-forgeDo not use pip to install kivy if you’re using Anaconda, unless you’re installing from source.10

2.3 Installing Kivy’s dependenciesKivy supports one or more backends for its core providers. E.g. it supports glew, angle, and sdl2 for thegraphics backend on Windows. For each category (window, graphics, video, audio, etc.), at least onebackend must be installed to be able to use the category.To facilitate easy installation, we provide extras require groups that will install selected backends to ensure a working Kivy installation. So one can install Kivy more simply with e.g. pip install“kivy[base,media,tuio]” . The full list of selectors and the packages they install is listed in setup.py.The exact packages in each selector may change in the future, but the overall goal of each selector willremain as described below.We offer the following selectors:base: The minimum typical dependencies required for Kivy to run, notvideo/audio.includingmedia: Only the video/audio dependencies required for Kivy to be able to play media.full: All the typical dependencies required for Kivy to run, including video/audio andmost optional dependencies.dev: All the additional dependencies required to run Kivy in development mode (i.e. itdoesn’t include the base/media/full dependencies). E.g. any headers required forcompilation, and all dependencies required to run the tests and creating the docs.tuio: The dependencies required to make TUIO work (primarily oscpy).The following selectors install backends packaged as wheels by kivy under the Kivy deps namespace.They are typically released and versioned to match specific Kivy versions, so we provide selectors tofacilitate installation (i.e. instead of having to do pip install kivy kivy deps.sdl2 x.y.z,you can now do pip install "kivy[sdl2]" to automatically install the correct sdl2 for the Kivyversion).gstreamer: The gstreamer video/audio backend, if it’s available (currently only on Windows)angle: A alternate OpenGL backend, if it’s available (currently only on Windows)sdl2: The window/image/audio backend, if it’s available (currently only on Windows,on macOS and Linux it is already included in the main Kivy wheel).glew: A alternate OpenGL backend, if it’s available (currently only on Windows)Following are the kivy deps dependency wheels: gstreamer (optional)kivy deps.gstreamer is an optional dependency which is only needed for audio/video support. We only provide it on Windows, for other platforms it must be installed independently.Alternatively, use ffpyplayer instead. glew and/or anglekivy deps.glew and kivy deps.angle are for OpenGL. You can install both, that is no problem. It is only available on Windows. On other platforms it is not required externally.One can select which of these to use for OpenGL using the KIVY GL BACKEND environmentvariable: By setting it to glew (the default), angle sdl2, or sdl2. Here, angle sdl2 is asubstitute for glew but requires kivy deps.sdl2 be installed as well. sdl2kivy deps.sdl2 is for window/images/audio and optionally OpenGL. It is only available onWindows and is included in the main Kivy wheel for other platforms.11

2.4 Python glossaryHere we explain how to install Python packages, how to use the command line and what wheels are.2.4.1 Installing PythonKivy is written in Python and as such, to use Kivy, you need an existing installation of Python. Multipleversions of Python can be installed side by side, but Kivy needs to be installed as package under eachPython version that you want to use Kivy in.To install Python, see the instructions for each platform: Windows, macOS, Linux, RPi.Once Python is installed, open the console and make sure Python is available by typing python--version.2.4.2 How to use the command lineTo execute any of the pip or wheel commands given here, you need a command line (here also calledconsole, terminal, shell or bash, where the last two refer to Linux style command lines) and Python mustbe on the PATH.The default command line on Windows is the command prompt, short cmd. The quickest way to openit is to press Win R on your keyboard. In the window that opens, type cmd and then press enter.Alternative Linux style command lines on Windows that we recommend are Git for Windows or Mysys.Note, the default Windows command line can still be used, even if a bash terminal is installed.To temporarily add your Python installation to the PATH, simply open your command line and then usethe cd command to change the current directory to where python is installed, e.g. cd C:\Python37.If you have installed Python using the default options, then the path to Python will already be permanently on your PATH variable. There is an option in the installer which lets you do that, and it isenabled by default.If however Python is not on your PATH, follow the these instructions to add it: Instructions for the windows command line Instructions for bash command lines2.4.3 What is pip and what are wheelsIn Python, packages such as Kivy can be installed with the python package manager, named pip(“python install package”).When installing from source, some packages, such as Kivy, require additional steps, like compilation.Contrary, wheels (files with a .whl extension) are pre-built distributions of a package that has alreadybeen compiled. These wheels do not require additional steps when installing them.When a wheel is available on pypi.org (“Python Package Index”) it can be installed with pip. For example when you execute python -m pip install kivy in a command line, this will automaticallyfind the appropriate wheel on PyPI.When downloading and installing a wheel directly, use the command python -m pip install wheel file name , for example:python -m pip install C:\Kivy-1.9.1.dev-cp27-none-win amd64.whl12

2.4.4 What are nightly wheelsEvery day we create a snapshot wheel of the current development version of Kivy (‘nightly wheel’).You can find the development version in the master branch of the Kivy Github repository.As opposed to the last stable release (which we discussed in the previous section), nightly wheels containall the latest changes to Kivy, including experimental fixes. For installation instructions, see Pre-release,pre-compiled wheels.Warning: Using the latest development version can be risky and you might encounter issues duringdevelopment. If you encounter any bugs, please report them.13

14

CHAPTERTHREEA FIRST APPImmerse yourself in the world of Kivy with your first App.The Pong Game Tutorial introduces the fundamental design patterns and the application developmentprocess. As you follow the tutorial, you will create a simple app. You will also learn how to run the appon your OS. The simple steps in the tutorial introduce elegant, useful concepts that you will use overand over again in app development.The Pong Game Tutorial is the most important article in the road map. It lays the foundation for the concepts that you will learn more about later. Each of the other articles expands on one of those concepts.15

16

CHAPTERFOURPROPERTIESKivy introduces a new way of declaring properties within a class. Before:class MyClass(object):def init (self):super(MyClass, self). init ()self.numeric var 1After, using Kivy’s properties:class MyClass(EventDispatcher):numeric var NumericProperty(1)These properties implement the Observer pattern. They help you to: Easily manipulate widgets defined in the Kv language Automatically observe any changes and dispatch functions/code accordingly Check and validate values Optimize memory managementTo use them, you have to declare them at class level. That is, directly in the class, not in any method ofthe class. A property is a class attribute that will automatically create instance attributes. Each propertyby default provides an on propertyname event that is called whenever the property’s state/valuechanges.Kivy provides the following properties: NumericProperty, StringProperty, ListProperty,ObjectProperty, BooleanProperty, BoundedNumericProperty, OptionProperty,ReferenceListProperty, AliasProperty, DictProperty, VariableListProperty,ConfigParserProperty, ColorPropertyFor an in-depth explanation, take a look at Properties.17

18

CHAPTERFIVEKV DESIGN LANGUAGEKivy provides a design language specifically geared towards easy and scalable GUI Design. The language makes it simple to separate the interface design from the application logic, adhering to the separation of concerns principle. For example:In the above code : LoginScreen :##GridLayout: ##rows: 2 #every class in your app can be represented by a rule likethis in the kv filethis is how you add your widget/layout to the parent(note the indentation).this how you set each property of your widget/layoutThat’s it, that’s how simple it is to design your GUI in the Kv language. For a more in-depth understanding, please refer to the Kv language documentation.19

20

CHAPTERSIXEVENTSKivy is mostly event-based, meaning the flow of the program is determined by events.Clock eventsThe Clock object allows you to schedule a function call in the future as a one-time event withschedule once(), or as a repetitive event with schedule interval().You can also create Triggered events with create trigger(). Triggers have the advantage of beingcalled only once per frame, even if you have scheduled multiple triggers for the same callback.Input eventsAll the mouse click, touch and scroll wheel events are part of the MotionEvent, extended by InputPostprocessing and dispatched through the on motion event in the Window class. This event thengenerates the on touch down(), on touch move() and on touch up() events in the Widget.For an in-depth explanation, have a look at Input management.Class eventsOur base class EventDispatcher, used by Widget, uses the power of our Properties for dispatchingchanges. This means when a widget changes its position or size, the corresponding event is automatically fired.In addition, you have the ability to create your own events using register event type(), as theon press and on release events in the Button widget demonstrate.Another thing to note is that if you override an event, you become responsible for implementing all itsbehaviour previously handled by the base class. The easiest way to do this is to call super():def on touch down(self, touch):if super().on touch down(touch):return Trueif not self.collide point(touch.x, touch.y):return False(continues on next page)21

(continued from previous page)print('you touched me!')return TrueGet more familiar with events by reading the Events and Properties documentation.22

CHAPTERSEVENNON-WIDGET STUFFAnimation is used to change a widget’s properties (size/pos/center etc.) to a target valuewithin a target time. Various transition functions are provided. You can use them to animatewidgets and build very smooth UI behaviours.Atlas is a class for managing texture maps,i.e. packing multiple textures into one image.This allows you to reduce the number of imagesloaded and thus speed up the application start.Clock provides you with a convenient way toschedule jobs at set time intervals and is preferred over sleep(), which would block the kivyevent loop. These intervals can be set relative tothe OpenGL drawing instructions, before or after.The Clock also provides you with a way to create triggered events that are grouped together andcalled only once before the next frame.UrlRequest is useful for asynchronous requests that do not block the event loop. You canuse it to manage the progress of URL requests viacallbacks. schedule once()schedule interval()unschedule()create trigger()23

24

CHAPTEREIGHTLAYOUTSLayouts are containers used to arrange widgets in a particular manner.AnchorLayout: Widgets can be anchored to the ‘top’, ‘bottom’, ‘left’, ‘right’ or ‘center’.BoxLayout: Widgets are arranged sequentially, in either a ‘vertical’ or a ‘horizontal’ orientation.FloatLayout: Widgets are essentially unrestricted.RelativeLayout: Child widgets are positioned relative to the layout.GridLayout: Widgets are arranged in a grid defined by the rows and cols properties.PageLayout: Used to create simple multi-page layouts, in a way that allows easy flippingfrom one page to another using borders.ScatterLayout: Widgets are positioned similarly to a RelativeLayout, but they can betranslated, rotated and scaled.StackLayout: Widgets are stacked in a lr-tb (left to right then top to bottom) or tb-lr order.When you add a widget to a layout, the following properties are used to determine the widget’s sizeand position, depending on the type of layout:size hint: defines the size of a widget as a fraction of the parents size. Values are restrictedto the range 0.0 - 1.0 i.e. 0.01 1/100th of the parent size (1%) and 1. same size (100%).pos hint: is used to place the widget relative to the parent.The size hint and pos hint are used to calculate a widget’s size and position only if the value(s) arenot set to None. If you set these values to None, the layout will not position/size the widget and youcan specify the values (x, y, width, height) directly in screen coordinates.25

26

CHAPTERNINEDRAWINGEach widget has a canvas, i.e. a place to draw on. The canvas is a group of drawing instructions thatshould be executed whenever there is a change to the widget’s graphical representation.You can add two types of instructions to the canvas: context instructions and vertex instructions. Youcan add instructions either from Python code or from the kv file (the preferred way). If you add themvia the kv file, the advantage is that they are automatically updated when any property they dependon changes. In Python, you need to do this yourself.In both cases, the canvas of MyWidget is re-drawn whenever the position or the size of the widgetchanges.You can use the canvas.before or canvas.after groups to separate your instructions based onwhen you want them to be executed.For an in-depth look at how Kivy’s graphics are handled, look here.27

28

CHAPTERTENPACKAGING Create a package for Windows– Requirements– PyInstaller default hook Creating packages for macOS– Using Buildozer– Using PyInstaller and Homebrew Create a package for Android– Packaging with python-for-android– Packaging your application for the Kivy Launcher Create a package for iOS– Compile the distribution– Create an Xcode project– Customize the Xcode project– Known issues– FAQ29

30

CHAPTERELEVENDIVING INTo get straight into kivy, take a look at Welcome to Kivy.Kivy comes with a set of examples (Gallery of Examples) in the kivy installation/examplesdirectory. You should try modifying/improving/adapting them to your needs.Browse our wiki for info on related projects, tutorials and snippets.Understand the basics about Graphics.Take a look at the built-in Widgets.Follow the Programming Guide to get even more familiar with kivy.See how to use different Modules in the modules section, such as the Inspector for live inspection.Learn how to handle custom Input management.Familiarize yourself with the Kivy Framework.Kivy is open source, so you can contribute. Take a look at the Contributing section for guidelines.31

32

Part IIKIVY PROJECTThis part of the documentation explains the basic ideas behind Kivy’s design and why you’d want touse it.33

34

CHAPTERTWELVEPHILOSOPHYIn case you are wondering what Kivy is all about and what sets it apart from other solutions, thisdocument is for you.12.1 Why bother?Why would you want to use Kivy? After all, there are many great toolkits (or frameworks, or platforms)available out there – for free. You have Qt and Flash, to name just two good choices for applicationdevelopment. Many of these numerous solutions already support Multi-Touch, so what is it that makesKivy special and worth using?12.1.1 FreshKivy is made for today and tomorrow. Novel input methods such as Multi-Touch have become increasingly important. We created Kivy from scratch, specifically for this kind of interaction. That means wewere able to rethink many things in terms of human computer interaction, whereas older (not to mean‘outdated’, rather ‘well-established’) toolkits carry their legacy, which is often a burden. We’re not trying to force this new approach to using a computer into the corset of existing models (say single-pointermouse interaction). We want to let it flourish and let you explore the possibilities. This is what reallysets Kivy apart.12.1.2 FastKivy is fast. This applies to both application development and application execution speeds. We have optimized Kivy in many ways. We implement time-critical functionality on the C level to leverage thepower of existing compilers. More importantly, we also use intelligent algorithms to minimize costlyoperations. We also 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, especially drawing. That’s why we try to let the GPU do as much of the work as possible, thus increasingperformance considerably.35

12.1.3 FlexibleKivy is flexible. This means it can be run on a variety of different devices, including iOS and Android powered smartphones and tablets. We support all major operating systems (Windows, Linux, macOS). Beingflexible also means that Kivy’s fast-paced development allows it to adapt to new technologies quickly. Morethan once have we added support for new external devices and software protocols, sometimes even before they were released. Lastly, Kivy is also flexible in that it is possible to use it in combination with agreat number of different third-party solutions. For example, on Windows we support WM TOUCH,which means that any device that has Windows 7 Pen & Touch drivers will just work with Kivy. OnmacOS you can use Apple’s Multi-Touch capable devices, such as trackpads and mice. On Linux, youcan use HID kernel input events. In addition to that, we support TUIO (Tangible User Interface Objects)and a number of other input sources.12.1.4 FocusedKivy is focused. You can write a simple application with a few lines of code. Kivy programs are createdusing the Python programming language, which is incredibly versatile and 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.12.1.5 FundedKivy is actively developed by professionals in their field. Kivy is a community-influenced, professionally 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.12.1.6 FreeKivy 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.36

CHAPTERTHIRTEENCONTRIBUTINGThere 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 feedback, bug reports, feature requests,documentation improvements, advertisement & advocating, testing, graphics contributions and manyother ideas. Just talk to us if you want to help, and we will help you help us.13.1 DiscussionsDiscussions around Kivy development happens on Github’s issues and pull requests for specific things.For things that don’t fit in either, discussions happen on the #dev Discord channel, and on the kivy-devgoogle group. Please come ask for guidance if you are unsure about how to contribute, or you wantconfirmation about your ideas fitting in the project before working on them. If you want to ask for —or contribute — support, you can join the #support Discord chan

Android python-for-android python-for-android iOS kivy-ios kivy-ios Anaconda conda — 2.1Using pip The easiest way to install Kivy is with pip, which installs Kivy using either a pre-compiled wheel, if available, otherwise from source (see below). Kivy provides pre-compiled wheels for the su