EzDev.org

kivy

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.


Why can't this Python multiprocessing process be terminated from Kivy?

I'm trying to run a django development server from within a Kivy application. This did work out quite well so far.

Now i want to allow the user to continue working with the program while the server is running. My idea was to create a multiprocessing.Process for the httpd.serve_forever() to avoid a complete lock of the main program. Did work well. This is the code in my internal_django module:

import multiprocessing
import os
import time

from wsgiref.simple_server import make_server

def django_wsgi_application():

    PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
    settings_module = "djangosettings"#%s.djangosettings" % PROJECT_ROOT.split(os.sep)[-1]

    os.environ.update({"DJANGO_SETTINGS_MODULE":settings_module})

    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()

    return application


class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class DjangoServer():
    __metaclass__ = Singleton

    def start(self):
        self.httpd = make_server('', 8000, django_wsgi_application())
        self.server = multiprocessing.Process(target=self.httpd.serve_forever)
        self.server.start()
        print "Now serving on port 8000..."
        print "Server Process PID = %s" %self.server.pid

    def stop(self):
        print("shutdown initiated")
        print "Server Process PID = %s" %self.server.pid
        while self.server.is_alive():
            self.server.terminate()
            print("Server should have shut down")
            time.sleep(1)
        print("Server is_alive: %s" %self.server.is_alive())
        self.server.join()
        print("server process joined")



if __name__ == "__main__":
    server = DjangoServer()
    server.start()
    time.sleep(3)
    server.stop()

When i run this code, everything works as expected. This is what is being put out in the console:

Now serving on port 8000...
Server Process PID = 1406
shutdown initiated
Server Process PID = 1406
Server should have shut down
Server is_alive: False
server process joined

Next step was to provide a way to stop the server from within the Kivy application. For that i just wanted to use my DjangoServer class as i did before:

from internal_django import DjangoServer

class StartScreen(Screen): 
    def start_server(self):
        server = DjangoServer()
        server.start()


class StopScreen(Screen):  
    def stop_server(self):
        server = DjangoServer()
        server.stop()

But when doing so, the process once started never quits. My first idea was that the Singleton did not work as expected, and that i try to quit the wrong process. but as you can see in the output, the PID's are identical. The server receives the terminate command, but just continues to work. This is what the console looks like:

Now serving on port 8000...
Server Process PID = 1406
shutdown initiated
Server Process PID = 1406
Server should have shut down
Server should have shut down
Server should have shut down
Server should have shut down
Server should have shut down
Server should have shut down
Server should have shut down
Server should have shut down

(and so on, until i manually kill the server process)

Am i using multiprocessing in a completely wrong way? Is Kivy somehow interfering with the process?


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)

Kivy ObjectProperty to update label text

I am working on creating a kivy user interface to display the values generated by a data model I've written as a standard python object. In essence, I would like the user to be able to press a button, which would change the underlying data model and the results of this change would be automatically updated and displayed. It is my understanding that this can be implemented using kivy properties (in this case, ObjectProperty).

Here is some example code:

import kivy
kivy.require('1.7.0')

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
from kivy.lang import Builder

Builder.load_string("""
<RootWidget>:
    cols: 2
    Label:
        text: "Attribute a:"
    Label:
        text: root.data_model.a
    Label:
        text: "Attribute b:"
    Label:
        text: root.data_model.b
    Label:
        text: "Attribute c:"
    Label:
        text: root.data_model.c
    Button:
        text: "Make data_model.a longer"
        on_press: root.button_press()
    Button:
        text: "Make data_model.b shorter"
        on_press: root.button_press2()
""")


class DataModel(object):
    def __init__(self):
        self.a = 'This is a'
        self.b ='This is b'

    @property
    def c(self):
        return self.a + ' and ' + self.b

class RootWidget(GridLayout):
    data_model = ObjectProperty(DataModel())

    def button_press(self, *args):
        self.data_model.a = 'This is a and it is really long now'
        print self.data_model.c

    def button_press2(self, *args):
        self.data_model.b = 'B'
        print self.data_model.c

class TestApp(App):
    def build(self):
        return RootWidget()

app = TestApp()
app.run()

The desired result is for when user presses either button, the labels would automatically update to show the new properties. As can be seen by the print statements, the data_model is getting updated correctly. However, none of the labels are updating. Can someone clarify how to do this?


Source: (StackOverflow)

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

Kivy=*.kv;

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
[settings]
# default extension used when saving files
extension=kv

# single comments, like # in this file
comment_single=#

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

[indentation]
width=4
# 0 is spaces, 1 is tabs, 2 is tab & spaces
type=0

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:

./distubute.sh -m "kivy"

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

Why?

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

Screenshot


Source: (StackOverflow)

Simple kivy tab example

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

from kivy.app 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)

      tb_panel.add_widget(th_text_head)
      tb_panel.add_widget(th_img_head)
      tb_panel.add_widget(th_btn_head)          

      return tb_panel

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

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

import kivy 
kivy.require('1.0.5')

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

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

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

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

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

and the kv file is :

#:kivy 1.0.5 

<loginView>: 
    status:result 
    Label: 
         text:"Contacts Manager" 
         pos:600,600 
         font_size:40 


    Label: 
         text:"Username" 
         pos:450,400 

    Label: 
         text:"Password" 
         pos:450,300 

    TextInput: 
         multiline:False 
         pos:600,425 
         size:200,45 
         font_size:20 
         id:username 

    TextInput: 
         multiline:False 
         pos:600,325 
         password:True 
         size:200,45 
         font_size:20 
         id:password 
    Button: 
         text:"Login" 
         size:100,50 
         pos:600,250 
         on_press:root.validate(username.text,password.text) 
    Label: 
         text:"" 
         pos:600,100 
         id:result 
<afterLogin>: 
    Label: 
         text:"Welcome" 

How can I add this code into the default tab?


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:

# custombutton.py

from kivy.app import App
from kivy.uix.widget import Widget


class MyWidget(Widget):
    pass


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


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

And the accompanying kv file custombutton.kv:

#:kivy 1.7.2

<MyWidget>:
    canvas:
        Color:
            rgb: (0.93, 0.93, 0.93)
        Rectangle:
            pos: self.pos
            size: self.size

    Button:
        center: self.parent.center
        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?

Thanks!


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 kivy.app import App
    from kivy.uix.widget import Widget
    from kivy.graphics 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__':
        MyPaintApp().run()


Source: (StackOverflow)

Passing image object as a button background in Kivy

In Kivy, is there a way to pass image object as a button background, instead of image file name?

button.background_normal property accepts only strings. I would like to customize image properties, such as allow_stretch = False.

If that succeeds, how can I specify image alignment inside a button, eg. to make it top-left aligned?


Source: (StackOverflow)

How do you check for keyboard events with kivy?

So, awhile ago, I started teaching myself kivy. I started with the main kivy website and went through its pong making tutorial and upon finishing that I decided to try and give it key input. I just can't seem to find any kind of guide to key input with kivy! Anyone know some kind of tutorial or can provide some easy to understand code? I did look at the Keyboard Listener in the examples folder of kivy, but I'm not quite sure how to use that if I'm supposed to.

Thanks for any assistance.


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

<CircleWidget>:
    canvas:
        Color:
            rgba: self.r,1,1,1
        Ellipse:
            pos: self.pos
            size: self.size

Here's the application circletest.py. 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
kivy.require('1.4.1')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget

Builder.load_file('circletest.kv')

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()
        parent.add_widget(w)
        return parent

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

Can anyone see the problem?

UPDATE

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:

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
        break

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
                break
        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...

    package org.renpy.android;

//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;
import android.app.Activity;

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;
        //updateListeners(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 {
                Looper.prepare();
                 lm = (LocationManager) currActivity.getSystemService( Context.LOCATION_SERVICE );
                 lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, minTime, minDistance, locationListener );
                 Looper.loop();

                }
            catch ( Exception e ) {
                e.printStackTrace();
            }
          }

        } );
        return gpsThread;    
    }
    //gpsThread.start();

}

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('org.renpy.android.KivyGps')

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

else:
    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 )
gpsThread.start()

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

Source: (StackOverflow)

Drawing SVG on Kivy canvas

I am new to Kivy. i need to create a classic analog clock.

My Question is: how to draw svg graphics into kivy canvas?


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

#uitest.kv
<TestForm>:
    canvas:
        Rectangle:
            pos: self.center_x, 0
            size: 10, self.height

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

<TestForm2>:
    canvas:
        Rectangle:
            pos: self.center_x, 0
            size: self.height, 10

My main python file runs the app, and returns the first widget

#main.py
from testform import TestForm
from kivy.app import App

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

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

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: http://kivy.org/docs/api-kivy.uix.screenmanager.html 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)