Open source Python framework for creating NUI applications, running on Windows, Linux, OS X, Android and iOS Kivy: Cross-platform Python Framework for NUI Development open source python framework for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps.

Custom syntax highlighting in Geany

I am trying to create custom syntax highlighting for Kivy '.kv' files in the Geany editor. Although the specific filetype seems irrelavant to the issue I'm having, as any efforts I make at getting syntax highlighting to work for a custom filetype results in a completely non-highlighted file. I believe I have done my homework on this, and nothing seems to work.

I have added the following to ~/.config/geany/filetype_extensions.conf


I also have a custom type definition file named 'filetypes.Kivy.conf' in ~/.config/geany/filedefs/. I have tried basing this file off several of the stock type definition files in /usr/share/geany/ and the file never gets any syntax highlighting applied in Geany. Right now, just for experimentation's sake, my 'filetypes.Kivy.conf' file looks like this:

# For complete documentation of this file, please see Geany's main documentation
# default extension used when saving files

# single comments, like # in this file

# all items must be in one line
primary=size canvas
secondary=pos size

# 0 is spaces, 1 is tabs, 2 is tab & spaces

This is very loosly based on the stock XML definition file, but like I said I've tried many other stock files. In many cases I only changed the 'extension=' value to kv and still no highlighting was applied, even though going to Document>Set Filetype in Geany and choosing virtually any random filetype (besides my custom entry) would yeild some sort of highlighting within my .kv file. This is even the case when using the unmodified contents of a stock definition which otherwise works fine on my .kv file when specifically selected in Geany!

Also, the Kivy filetype is listed and selected by default in Document>Set Filetype within Geany, so I must be doing something right here!

I realize this similar question has been asked, but the solutions seem irrelavent to my case, as I've tried every related topic on this and many other sites. My Geany version is 1.22 and I'm running Arch Linux. This is driving me nuts - any suggestions?

Thank you!

Source: (StackOverflow)

No Android SDK environment set for Kivy in Ubuntu 12.04

I've written a game for Android using Python and Kivy. I have downloaded android-sdk-linux and added its path to .bashrc. I've also cloned the python-for-android project to create an apk package of my program. But when I write the following command as instructed in the Kivy manual, I get an error:

./ -m "kivy"

    Check build dependencies for Ubuntu
    Check enviromnent
    No ANDROIDSDK environment set, abort


This is a picture of my ./ in $android-sdk-linux/tools:


Source: (StackOverflow)

Simple kivy tab example

I am new to Android development using Kivy. I have created a tab structure like below:

from import App
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.tabbedpanel import TabbedPanelHeader
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.image import Image

class TabbedPanelApp(App):
  def build(self):
      tb_panel= TabbedPanel()

      # Create text tab          
      th_text_head = TabbedPanelHeader(text='Text tab')
      th_text_head.content= Label(text='This is my text content')

      # Create image tab
      th_img_head= TabbedPanelHeader(text='Image tab')
      th_img_head.content= Image(source='sample.jpg',pos=(400, 100), size=(400, 400))

      # Create button tab
      th_btn_head = TabbedPanelHeader(text='Button tab')
      th_btn_head.content= Button(text='This is my button',font_size=20)


      return tb_panel

if __name__ == '__main__':

I want to add the login widget to the default tab. The code for login widget is:

import kivy 

from kivy.uix.gridlayout import GridLayout 
from kivy.uix.boxlayout import BoxLayout 
from kivy.uix.button import Button 
from import App 
from kivy.lang import Builder 
from kivy.uix.widget import Widget 
from import ObjectProperty, StringProperty 

class loginView(Widget): 
    def validate(self,username,password): 
        print "user - ", username
        print "pwd - ", password
        if username == password: 
            print "in if - ", username,password     
            self.status.text="Login sucess" 
            self.status.text="Login failed" 

class afterLogin(Widget): 
    def dumb(self): 
        l = BoxLayout(cols="2") 
        btn = Button(text="ad") 
        print "flag" 

class mainClass(App): 
    def build(self): 
        return loginView()  

if __name__ == '__main__': 

and the kv file is :

#:kivy 1.0.5 

         text:"Contacts Manager" 





How can I add this code into the default tab?

Source: (StackOverflow)

Kivy: crossplatform notification icon

I want to create a cross-platform application (Ubuntu and Android) with a notification icon. Is there a standard way to create such an app using Kivy?

Source: (StackOverflow)

Changing the background color of a Button in Kivy

I'm new to Kivy and having trouble specifying the background color of a Button. Here's my simple example:


from import App
from kivy.uix.widget import Widget

class MyWidget(Widget):

class CustomButtonApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':

And the accompanying kv file custombutton.kv:

#:kivy 1.7.2

            rgb: (0.93, 0.93, 0.93)
            pos: self.pos
            size: self.size

        font_size: 14
        height: 28
        background_color: (1.0, 0.0, 0.0, 1.0)
        text: "I'm a Button"

I'm sure I'm missing something obvious, but I've been messing with this for over an hour now and getting nowhere. The button seems to get colored a hint of very dark red:

enter image description here

Is this not the way to specify the background color for a Button in Kivy?


Source: (StackOverflow)

Tab/Enter (and other keystrokes) handling in Kivy's TextInput widgets

I'm writing an app using Kivy framework and I stumbled upon a minor but annoying problem: I don't know how to handle Tab/Enter/Arrow keys in text fields so that pressing either of them would dispatch an event, eg. switch the focus (jump) to another TextInput or launch something like send_form()

Could anyone please shed some light on this issue?

Source: (StackOverflow)

why does right-clicking create an orange dot in the center of the circle?

Why does the first widget example in kivy lead to an orange circle in the middle of the yellow one when you right click on the canvas and a pure yellow one when you left click?

    from import App
    from kivy.uix.widget import Widget
    from import Color, Ellipse

    class MyPaintWidget(Widget):
        def on_touch_down(self, touch):
            with self.canvas:
                Color(1, 1, 0)
                d = 30.
                Ellipse(pos=(touch.x - d/2, touch.y - d/2), size=(d, d))

    class MyPaintApp(App):
        def build(self):
            return MyPaintWidget()

    if __name__ == '__main__':

Source: (StackOverflow)

How do I change the color of my widget in Kivy at run time?

I'm having trouble changing the color of a simple widget in Kivy. I can set the color when I create the widget, but I can't change it afterwards.

Here is the simple layout definition file circletest.kv. It defines a circle where the color (actually just the r, from rgba), position and size are all linked to variables in the widget class.

#:kivy 1.4.1

            rgba: self.r,1,1,1
            pos: self.pos
            size: self.size

Here's the application It creates and displays the simple widget. The color and position are successfully set when the object is created. When the widget is clicked the widget can change it's own position, but when I try to change the color nothing happens.

import kivy
from import App
from kivy.lang import Builder
from kivy.uix.widget import Widget


class CircleWidget(Widget):

    def __init__(s, **kwargs):
        s.size= [50,50]
        s.pos = [100,50]
        s.r = 0
        super(CircleWidget, s).__init__(**kwargs)

    def on_touch_down(s, touch):
        if s.collide_point(touch.x,touch.y):    
            s.pos = [s.pos[1],s.pos[0]]           # This works
            s.r = 1.0                       # <---- This does nothing!

class TestApp(App):

    def build(s):
        parent = Widget()
        w = CircleWidget()
        return parent

if __name__ == '__main__':

Can anyone see the problem?


Still not sure what the answer to this question is, but I do have a work around:

In the .kv file I pointed the color to a variable in my object. Works for extracting the initial color:

    rgba: self.col

When I want to change the color from the .py file I loop through all the instructions in the canvas and modify the first one of type "Color". Obviously this is a hack, and won't work on widgets with more than one Color: property:

for i in s.canvas.get_group(None):
    if type(i) is Color:
        i.r, i.g, i.b, i.a = v

I wrapped that all up in a property so it's neat to use:

class CircleWidget(Widget):

    def get_col(s):
        return s._col

    def set_col(s,v):
        for i in s.canvas.get_group(None):
            if type(i) is Color:
                i.r, i.g, i.b, i.a = v
        s._col = v

    col = property(get_col, set_col)

    def __init__(s, **kwargs):
        s.size= [50,50]
        s.pos = [100,50]
        s._col = (1,1,0,1)
        super(CircleWidget, s).__init__(**kwargs)

    def on_touch_down(s, touch):
        if s.collide_point(touch.x,touch.y):    
            s.col = (s.col[::-1]) # Set to some other color

Seems to work for now. Please let me know if you know a better way of doing this. I'm sure there must be a simpler way, and that I'm missing something obvious!

Source: (StackOverflow)

How to make GPS-app for android using kivy, pyjnius?

Im new in KIVY, pyjnius and python-android. I need to make simple app for android, which shows GPS coordinates. But, as i said, i'm new in kivy and pyforandroid. Can somebody show/give me example,which shows my coordinates in simple kivy-label-widget? Thanks a lot!

I ve tried to do something like this but...


//import java.util.ArrayList;
//import java.util.List;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import java.lang.Thread;

public class KivyGps {
    LocationManager lm;
    Thread gpsThread;
    public long minDistance = 1;
    public int  minTime = 1000;

   static class KivyLocationListener implements LocationListener {

    public Location lastLocation = new Location("Other");
    //private List<LocationListener> listeners = new ArrayList<LocationListener>();

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        lastLocation = location;

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

        // TODO Auto-generated method stub
        return lastLocation;


    static public KivyLocationListener locationListener = new KivyLocationListener();
    public Thread init(final Activity currActivity) {

        gpsThread = new Thread( new Runnable() {

          public void run() {
            try {
                 lm = (LocationManager) currActivity.getSystemService( Context.LOCATION_SERVICE );
                 lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, minTime, minDistance, locationListener );

            catch ( Exception e ) {

        } );
        return gpsThread;    


In python

from jnius import autoclass

LocationListener = autoclass('android.location.LocationListener')
LocationManager = autoclass('android.location.LocationManager')
LocationProvider = autoclass('android.location.LocationProvider')
Location = autoclass('android.location.Location')
Looper = autoclass('android.os.Looper')
Context = autoclass('android.content.Context')
KivyGps = autoclass('')

currentActivity = cast('', PythonActivity.mActivity)
lm = currentActivity.getSystemService( Context.LOCATION_SERVICE)
if lm.isProviderEnabled( LocationManager.GPS_PROVIDER ):
    print 'CON GPS'

    print 'SIN GPS'

lps = lm.getAllProviders()
for lp in lps.toArray():
    print lp
#Arreglar problema de derechos ACCESS_FINE_LOCATION en Kivy Launcher
lp = lm.getProvider('gps')

ll = KivyGps.locationListener
kgps = KivyGps()
gpsThread = kgps.init( currentActivity )

loc = ll.getCurrentLocation()
if loc:
    print loc.getLatitude()
    print loc.getLongitude()

Source: (StackOverflow)

Switching kivy widgets

I am using the Kivy python library.

I have two widgets defined.

When the program runs, I run the first widget.

When that widgets button is pressed, I want it to dissapear and be replaced with the second widget.

Here is the .kv for the two widgets

            pos: self.center_x, 0
            size: 10, self.height

        size: root.size
        padding: 40
            text: 'Hello'
            on_release: root.testCallback()

            pos: self.center_x, 0
            size: self.height, 10

My main python file runs the app, and returns the first widget
from testform import TestForm
from import App

class UITestApp(App):
    def build(self):
        return TestForm()

# Main launching point
if __name__ in ('__main__', '__android__'):

My first widget has a callback. This is where the code-in-question belongs

from testform2 import TestForm2
from kivy.uix.widget import Widget

class TestForm(Widget):
    def testCallback(self):
        TestForm2() # Code in question goes here. @TODO replace this widget with TestForm2 widget.

The idea here is to have a user interface manager. This manager doesn't run the UI like a tree, but like a list and stack. The list holds instances of all my UI Forms. The stack holds the traversal of said forms, whenever we jump to a form we push it to the stack and "render" or whatever that one.

EDIT: I chose my answer, but in my searches I also found the Screen object: Personally, the clear() and add() commands are more powerful, but the screen takes a lot of that out of your hands if you're interested. Transition effects too.

Source: (StackOverflow)

Kivy button text alignment issue

I am trying to develop an email application in Kivy, basically just as an exercise to learn the in's and out's of the framework... I am trying to create the initial window and have reached a bit of a stumbling block! The idea is that it will simply display a list of emails in the inbox, much like any basic email app on a mobile device.

The problem I'm having is that I can't figure out how to get the text of each list item (which is a just a button) to align properly. Using "halign='left'" in my button will make the text align left, but only relative to each button; it's still centered within each button.

My actual app is a bit large to post, so this is a quick and dirty example I made from a stock Kivy example. (I realize this code isn't perfect... like I said quick and dirty for examples sake... it does work though!) So as you can see, the two rows of text on each button align with each other, but they don't all align overall. Can anyone suggest what I would do to make all the text align at, say, 10px from the left of each button? I did find one relative sounding item on StackOverflow, but it didn't really answer the question for example, it seemed to deal more with using images on buttons. I am new to Kivy, but I've read through the tutorials and documentation, as well as searched Google extensively - so any help would be greatly appreciated!

import kivy

from import App
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout

import random

class ScrollViewApp(App):

    def build(self):
        # create a default grid layout with custom width/height
        layout = GridLayout(cols=1, spacing=10, size_hint=(None, None),

        # when we add children to the grid layout, its size doesn't change at
        # all. we need to ensure that the height will be the minimum required to
        # contain all the childs. (otherwise, we'll child outside the bounding
        # box of the childs)

        # add button into that grid
        for i in range(30):
            btn = Button(text=str(i * random.random()) + '\n' + str(i * random.random()),
                         size=(300, 40),
                         size_hint=(None, None),

        # create a scroll view, with a size < size of the grid
        root = ScrollView(size_hint=(None, None))
        root.size = (Window.width, Window.height) =

        return root

if __name__ == '__main__':


Source: (StackOverflow)

Rotating an object on a touch event in kivy

I'm working on making a circle that will spin kind of like a large dial. Currently, I have an arrow at the top to show which direction the dial is facing. I'd like its behavior to be kind of like an old timey rotary phone, such that while your finger/cursor is down you can rotate it, but it'll (slowly) yank back to top after you let go.

Here's what my object looks like:

enter image description here

And here's my code:

import kivy
import math

from random import random
from import App
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.relativelayout import RelativeLayout
from import Color, Ellipse, Rectangle

class MinimalApp(App):
    title = 'My App'
    def build(self):
        root = RootLayout()

class RootLayout(AnchorLayout):

class Circley(RelativeLayout):
    angle = 0
    def on_touch_down(self, touch):
        ud = touch.ud
        ud['group'] = g = str(touch.uid)
        return True
    def on_touch_move(self, touch):
        ud = touch.ud
#        print(touch.x, 0)
#        print(
#        print(0, touch.y)
#        print(touch.x -[0], touch.y -[1])
        y = (touch.y -[1])
        x = (touch.x -[0])
        calc = math.degrees(math.atan2(y,x))
        angle = calc if calc > 0 else (360 + calc)
    def on_touch_up(self, touch):
        ud = touch.ud
        return True

if __name__ == '__main__':

And the kv:

#:kivy 1.7.2
#:import kivy kivy

    anchor_x: 'center'                              # I think this /is/ centered
    anchor_y: 'center' 
            rgba: 0.4, 0.4, 0.4, 1
            pos: self.pos
            size: self.size
        anchor_x: 'center'                          # this is /not/ centered.
        anchor_y: 'center' 
                rgba: 0.94, 0.94, 0.94, 1
                angle: self.angle
                axis: 0, 0, 1
                source: 'arrow.png'
                size: min(self.size), min(self.size)
                pos: 0.5*self.size[0] - 0.5*min(self.size), 0.5*self.size[1] - 0.5*min(self.size)
                    text: unicode(self.size)    # this is /not/ appearing
                    color: 1,0,0,1

Parts of that are borrowed from the kivy touchtracer demo, and from this SO question.

You can see I have a calculation that is correctly printing the angle between the origin of the circle and the touch event (not sure how this'll respond to multiple fingers, haven't thought that far through), but not sure how to integrate this into a "spinning" feedback event in the interface.

Source: (StackOverflow)

Kivy, Eclipse and PyDev (also PyPy)

According to this post:!topic/kivy-users/n7c3thksnzg, it is possible to use Eclipse as an IDE for Kivy through PyDev. However, I didn't understand the instructions. Can anyone please elaborate on how to connect Kivy with Eclipse.

Note: I'm on a Windows machine. Also, is it possible to use PyPy instead of the Python Interpreter?


Source: (StackOverflow)

QPython or Kivy for Android programming with Python - producing installable apk

Having read several Q&A's on SO, I realize that one has 2 options i.e. QPython and Kivy to do programming for Android, however, apparently both take different approaches. I am trying to validate my understanding and see if I am missing some key piece of information.

  • QPython allows usage of Kivy library for developing graphical applications
  • QPython and Kivy both use SL4A, while QPython has expanded standard SL4A (or it's bindings for Python) by adding some NFC and similar functions
  • QPython is used to create python scripts that can use wide range of modules, libraries, but they need QPython installed to be executed on target device. There is no way to package script into an apk.
  • Kivy OTOH, allows developer to write applications that compile to apk, using their cloud based build system (alternative - local build system can be set up on Ubuntu Linux) [However, I noticed that most of the sample apk's that use Kivy are pretty large, in the 40MB range. Did I miss anything ?]
  • QPython apk has 2 version i.e. one for Python-2.7 and another one for Python-3.x. For Kivy, I'm not sure which version it is.
  • QPython example script ( doesn't seem to behave as expected, from latest QPython-3.x from Market, on an Android Kitkat (4.4.2) system. I get the dialog to enter text, but then I expect a Toast to popup, but nothing happens.
  • Get the impression that both QPython and Kivy are developed by a single developer each (or only one person is really active at present), and don't yet have a biggish community. [This is my biggest concern] I notice that there are 3-4 questions with 'qpython' tag on SO, and more than thousand with 'kivy'!
  • Also get the impression that at this moment Kivy development is somewhat more active (perhaps quite active), but for QPython I don't have a clear picture.
  • Kivy seems to be trying to expand the nature of application that could possibly be written using it, compare to QPython. There are API's like plyer and pyjnius that help expand the possibilities. Perhaps quite significantly, compared to QPython.
  • Both QPython and Kivy seem to be heavily under development. Program (/ script) crashes (/ failures) seem to be reported on both set of tools.

Overall, the opinion as a result (of above points) appears to swing in favour of Kivy, a bit more. Is the understanding correct ? Did I miss any crucial point ? This is not a rhetorical question, and I am looking for factual answers only.

Source: (StackOverflow)

How to configure Python Kivy for PyCharm on Windows?

I'm having trouble getting Kivy to work with PyCharm on Windows 7. I've managed to add most of the external libraries through File > Settings > Python interpreters > Paths Tab.

I'm using the Kivy version of Python. When I run a Kivy app that works fine with using the [right click > send to > kivy.bat] method in PyCharm, it gives me this error:

Failed modules
Python 2.7.3 (C:/Python27/python.exe) 
Generation of skeletons for the modules above will be tried again when the modules are updated or a new version of generator is available

I think that the problem might by something to do with cython, as my file fails to recognise the file, which is of the Cython *.pxd format.

If someone could please pointer me over to a windows config tutorial for PyCharm and Kivy or give me the solution to my problem, I would greatly appreciate it!

Source: (StackOverflow)