Application

The App class is the base for creating Kivy applications. Think of it as your main entry point into the Kivy run loop. In most cases, you subclass this class and make your own app. You create an instance of your specific app class and then, when you are ready to start the application’s life cycle, you call your instance’s App.run() method.

Creating an Application

Method using build() override

To initialize your app with a widget tree, override the build() method in your app class and return the widget tree you constructed.

Here’s an example of a very simple application that just shows a button:

'''
Application example using build() + return
==========================================

An application can be build if you return a widget on build(), or if you set
self.root.
'''

import kivy
kivy.require('1.0.7')

from kivy.app import App
from kivy.uix.button import Button


class TestApp(App):

    def build(self):
        # return a Button() as a root widget
        return Button(text='hello world')

if __name__ == '__main__':
    TestApp().run()

The file is also available in the examples folder at kivy/examples/application/app_with_build.py.

Here, no widget tree was constructed (or if you will, a tree with only the root node).

Method using kv file

You can also use the Kivy Language for creating applications. The .kv can contain rules and root widget definitions at the same time. Here is the same example as the Button one in a kv file.

Contents of ‘test.kv’:

#:kivy 1.0

Button:
        text: 'Hello world'

Contents of ‘main.py’:

'''
Application from a .kv
======================

The root application is created from the corresponding .kv. Check the test.kv
file to see what will be the root widget.
'''

import kivy
kivy.require('1.0.7')

from kivy.app import App


class TestApp(App):
    pass

if __name__ == '__main__':
    TestApp().run()

See kivy/examples/application/app_with_kv.py.

The relation between main.py and test.kv is explained in App.load_kv().

Application configuration

New in version 1.0.7.

Use the configuration file

Your application might want to have its own configuration file. The App is able to handle an INI file automatically. You add your section/key/value in the App.build_config() method by using the config parameters (instance of ConfigParser:

class TestApp(App):
    def build_config(self, config):
        config.setdefaults('section1', {
            'key1': 'value1',
            'key2': '42'
        })

As soon as you add one section in the config, a file is created on the disk, and named from the mangled name of your class:. “TestApp” will give a config file-name “test.ini” with the content:

[section1]
key1 = value1
key2 = 42

The “test.ini” will be automatically loaded at runtime, and you can access the configuration in your App.build() method:

class TestApp(App):
    def build_config(self, config):
        config.setdefaults('section1', {
            'key1': 'value1',
            'key2': '42'
        })

    def build(self):
        config = self.config
        return Label(text='key1 is %s and key2 is %d' % (
            config.get('section1', 'key1'),
            config.getint('section1', 'key2')))

Create a settings panel

Your application can have a settings panel to let your user configure some of your config tokens. Here is an example done in the KinectViewer example (available in the examples directory):

_images/app-settings.jpg

You can extend the default application settings with your own panel by extending the App.build_settings() method. Check the class:~kivy.uix.settings.Settings about how to create a panel, because you need a JSON file / data first.

Let’s take as an example the previous snippet of TestApp with custom config. We could create a JSON like this:

[
    { "type": "title",
      "title": "Test application" },

    { "type": "options",
      "title": "My first key",
      "desc": "Description of my first key",
      "section": "section1",
      "key": "key1",
      "options": ["value1", "value2", "another value"] },

    { "type": "numeric",
      "title": "My second key",
      "desc": "Description of my second key",
      "section": "section1",
      "key": "key2" }
]

Then, we can create a panel using this JSON to create automatically all the options, and link them to our App.config ConfigParser instance:

class TestApp(App):
    # ...
    def build_settings(self, settings):
        jsondata = """... put the json data here ..."""
        settings.add_json_panel('Test application',
            self.config, data=jsondata)

That’s all ! Now you can press F1 (default keystroke) to toggle the settings panel, or press the “settings” key on your android device. You can manually call App.open_settings() and App.close_settings() if you want. Every change in the panel is automatically saved in the config file.

However, you might want to know when a config value has been changed by the user, in order to adapt or reload your UI. You can overload the on_config_change() method:

class TestApp(self):
    # ...
    def on_config_change(self, config, section, key, value):
        if config is self.config:
            token = (section, key)
            if token == ('section1', 'key1'):
                print 'Our key1 have been changed to', value
            elif token == ('section1', 'key2'):
                print 'Our key2 have been changed to', value

One last note, the Kivy configuration panel is added by default in the settings instance. If you don’t want it, you can declare your Application like this:

class TestApp(App):
    use_kivy_settings = False
    # ...

Pause mode

New in version 1.1.0.

Warning

This mode is experimental, and designed for phones/tablets. There are some cases where your application could crash on resume.

On tablets and phones, the user can switch at any moment to another application. By default, your application will reach App.on_stop() behavior.

You can support the Pause mode: when switching to another application, the application goes into Pause mode and waits infinitely until the user switches back to your application. There is an issue with OpenGL on Android devices: you’re not ensured that the OpenGL ES Context is restored when your app resumes. The mechanism for restoring all the OpenGL data is not yet implemented into Kivy(we are looking for device with this behavior).

The current implemented Pause mechanism is:

  1. Kivy checks every frame, if Pause mode is activated by the Operating System, due to user switching to another application, phone shutdown or any other reason.
  2. App.on_pause() is called:
  3. If False is returned (default case), then App.on_stop() is called.
  4. Otherwise the application will sleep until the OS will resume our App
  5. We got a resume, App.on_resume() is called.
  6. If our app memory has been reclaimed by the OS, then nothing will be called.

Warning

Both on_pause and on_stop must save important data, because after on_pause call, on_resume may not be called at all.

class kivy.app.App(**kwargs)

Bases: kivy.event.EventDispatcher

Application class, see module documentation for more information.

Events :
on_start:

Fired when the application is being started (before the runTouchApp() call.

on_stop:

Fired when the application stops.

Parameters :
kv_directory: <path>, default to None

If a kv_directory is set, it will be used to get the initial kv file. By default, the file is searched in the same directory as the current App definition file.

build()

Initializes the application; will be called only once. If this method returns a widget (tree), it will be used as the root widget and added to the window.

Returns:None or a root Widget instance is no

self.root exist.

build_config(config)

New in version 1.0.7.

This method is called before the application is initialized to construct your ConfigParser object. This is where you can put any default section / key / value for your config. If anything is set, the configuration will be automatically saved in the file returned by get_application_config().

Parameters:config (ConfigParser) – Use this to add defaults section / key / value
build_settings(settings)

New in version 1.0.7.

This method is called when the user (or you) want to show the application settings. This will be called only once, the first time when the user will show the settings.

Parameters:settings (Settings) – Settings instance for adding panels
close_settings(*largs)

Close the previously opened settings panel.

Returns:True if the settings have been closed
config = None

Instance to the ConfigParser of the application configuration. Can be used to query some config token in the build()

directory

New in version 1.0.7.

Return the directory where the application live

get_application_config()

New in version 1.0.7.

Return the filename of your application configuration

get_application_icon()

Return the icon of the application.

get_application_name()

Return the name of the application.

static get_running_app()

Return the current runned application instance.

New in version 1.1.0.

icon = None

New in version 1.0.5.

Icon of your application. You can set by doing:

class MyApp(App):
    icon = 'customicon.png'

The icon can be located in the same directory as your main file.

load_config()

(internal) This function is used for returning a ConfigParser with the application configuration. It’s doing 3 things:

  1. Create an instance of a ConfigParser
  2. Load the default configuration by calling build_config(), then
  3. If exist, load the application configuration file, or create it if it’s not existing.
Returns:ConfigParser instance
load_kv()

This method is invoked the first time the app is being run if no widget tree has been constructed before for this app. This method then looks for a matching kv file in the same directory as the file that contains the application class.

For example, if you have a file named main.py that contains:

class ShowcaseApp(App):
    pass

This method will search for a file named showcase.kv in the directory that contains main.py. The name of the kv file has to be the lowercase name of the class, without the ‘App’ postfix at the end if it exists.

You can define rules and a root widget in your kv file:

<ClassName>: # this is a rule
    ...

ClassName: # this is a root widget
    ...

There must be only one root widget. See the Kivy Language documentation for more information on how to create kv files. If your kv file contains a root widget, it will be used as self.root, the root widget for the application.

name

New in version 1.0.7.

Return the name of the application, based on the class name

on_config_change(config, section, key, value)

Event handler fired when one configuration token have been changed by the settings page.

on_pause()

Event handler called when pause mode is asked. You must return True if you can go to the Pause mode. Otherwise, return False, and your application will be stopped.

You cannot control when the application is going to this mode. It’s mostly used for embed devices (android/ios), and for resizing.

Default is False.

New in version 1.1.0.

on_resume()

Event handler called when your application is resuming from the Pause mode.

New in version 1.1.0.

Warning

When resuming, OpenGL Context might have been damaged / freed. This is where you should reconstruct some of your OpenGL state, like FBO content.

on_start()

Event handler for the on_start event, which is fired after initialization (after build() has been called), 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).

open_settings(*largs)

Open the application settings panel. It will be created the very first time. Then the settings panel will be added to the Window attached to your application (automatically done by run())

Returns:True if the settings have been opened
options = None

Options passed to the __init__ of the App

root = None

Root widget set by the build() method or by the load_kv() method if the kv file contains 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 issuing a call to stopTouchApp().

title = None

New in version 1.0.5.

Title of your application. You can set by doing:

class MyApp(App):
    title = 'Custom title'
use_kivy_settings = True

New in version 1.0.7.

If True, the application settings will include also the Kivy settings. If you don’t want the user to change any kivy settings from your settings UI, change this to False.