Posts tagged ‘python’

Creating an Application in Kivy: Part 3

This article continues a series on creating a Kivy application. At the end of Part 2, we had a basic form for entering Jabber login details. In this part, we’ll hook up the login button to actually connect to the jabber server and download a Buddy List.

Make sure you’ve completed the previous two parts, or if you want to start from a clean slate, you can clone the end_part_two tag in my git repo for this project. Remember to do your own changes on a separate branch to avoid conflicts later.

git clone # or 'git pull' if you've cloned before and want to update
git checkout end_part_two
git checkout -b working_changes
source venv/bin/activate

Table Of Contents

Here are links to other parts of this tutorial.

  1. Part 1: Introduction to Kivy
  2. Part 2: A basic KV Language interface
  3. Part 3: Interacting with widgets and the user
  4. Part 4: Code and Interface Improvements
  5. Part 5: Rendering a Buddy List
  6. Part 6: ListView Interaction
  7. Part 7: Receiving messages and interface fixes
  8. Part 8: Width based layout
  9. Part 9: Deploying your Kivy application

Handling Events defines an event as “something that happens, esp. something important”. That’s a perfect description of events in Kivy. Kivy is firing events all the time, but we only have to pay attention to those that we consider important (in the upcoming example, clicking/touching the Login button is important). Every graphical toolkit I have ever used has some concept of events. The difference between Kivy and those other toolkits is that in Kivy, event dispatch and handling is sane and uncomplicated.

If an event is something that happens, then an event handler is something that reacts when an event occurs. Our event handler will eventually log into the server and display the Buddy List, but lets start by printing a quote from a humorous scene in the film Rush Hour. We do this by adding a method to the AccountDetailsForm class in


class AccountDetailsForm(AnchorLayout):
    def login(self):
        print("Click the goddamn button")

Remember in Part 1 I mentioned that object oriented programming allowed us to add functionality to existing classes? That’s what we are doing here. The AnchorLayout class has no idea what it might mean to “login” to something, but it makes sense for AccountDetailsForm to do so. So we add a method to the subclass named login. A method is just a function that is aware of which object it is attached to (that’s why it has the parameter self). At this point, we don’t care what object we are attached to, but it will become important soon.

So that method, which we named login, is an event handler. Actually, technically, it’s just a method that happens to handle an event, and we will hook it up by calling that method from the true event handler. Let’s do that next. We just need to add one property to the login Button in our orkiv.kv file:


        size_hint_y: None
        height: "40dp"
        text: "Login"
        on_press: root.login()

Kivy is really really good about making programmers do the minimal amount of work required. If you add this one line of code and run it, you can click the Login button repeatedly, and each time, the movie quote will show up on the terminal.

The Button widget in Kivy has a press event. The key to signifying an event handler is to add an on_<eventname> property. Now this is where the KV Language gets a little creepy. The code that comes after the event handler property name is standard Python. In fact, you could just use on_press: print("you clicked it") and it would work. Or if you wanted multiple lines of Python, you could put them on the next line, indented, as though the program code was a child widget.

Don’t ever do that. That’s my rule: never have two or more lines of python logic in a KV Language file. When you break this rule, make sure you know for certain that you have a good reason to do it and that you thought that reason all the way through. This will aide you in the future if you ever want to change the layout without trying to sift out the business logic that hasn’t changed. In my mind, the point of KV Language is to define layout and style. You should not mix logic (program code) with the styling. Instead, put the program code on the class in and use one line of logic to call that method.

There’s a small amount of magic going on here. The root variable in a KV Language file always refers to the object that is at the left-most indent in our current block. In this case, it’s the <AccountDetailsForm> class, which is the class containing the handy login method. KV Language has two other “magic” variables that you may find useful: app and self. app can be used anywhere in a KV Language file to refer to the object that inherits from Application; so the Orkiv object. Self refers to the current widget. If we called self.x() in the on_press handler, it would refer to the Login Button object itself.

Interacting with widgets

Now, let’s figure out how to get some values out of the textboxes in the form. To this end, we’ll need to refer to objects in the KV Language file from inside the associated class in our This requires a few sets of changes to both files. Let’s start with some minor additions to the elements of our form in orkiv.kv.


        text: "Server"
        id: server_input
        text: "Username"
        id: username_input
        text: "Password"
        password: True
        id: password_input

We’ve simply added an identifier to each of our TextInput boxes so that we can refer to them elsewhere in the code. Note that I gave them all consistent names ending in _input. Consistency is very important in programming. Your memory is not infallible, and it would be silly to overtax it by trying to remember that one box is named password and the other is named UserNameTextInput. After years of programming, this statement seems blatantly obvious to me. However, I am frequently frustrated by non-developers who supply (for example) csv files that use spaces and underscores interchangeably or vary the capitalization of identifiers that I need to sanitize before using in program code. Do yourself and everyone else who works with your code a favor and strive for consistency. One really good way to do this in Python code is to strictly follow the Python Style Guidelines even if you disagree with some of the rules. I strongly recommend using a pep-8 highlighter in your editor (I personally use SublimeLinter) to aid you in this pursuit.

Ok, back to the code! The key takeaway is that by giving these widgets an id, we can reference them in other parts of the KV Language file. Specifically, we can set them as the values of custom properties on the AccountDetailsForm class rule like so:


    anchor_y: "top"
    server_box: server_input
    username_box: username_input
    password_box: password_input

We have defined three custom Kivy properties (named server_box, username_box, and password_box) on the AccountDetailsForm class. Each of these properties is assigned a value of the id of one of the text boxes.

It is common to name the properties the same as the ids on the boxes they point to (see my diatribe on consistency above!). However, I chose not to do that here for pedagogical reasons; it’s clear from this example that a property name is a completely different thing from an identifier.

This is no different from setting a property that is meaningful to the parent class such as anchor_y.The difference is that the parent class (AnchorLayout) doesn’t know about them. Neither does the child class, yet, but we’ll now fix that in


from import ObjectProperty  # at top of file

class AccountDetailsForm(AnchorLayout):
    server_box = ObjectProperty()
    username_box = ObjectProperty()
    password_box = ObjectProperty()

We added an import statement so we can access Kivy’s ObjectProperty class. Then we specified three instances of this fancy property on the AccountDetailsForm. These instances must have the same names as the properties defined in the KV Language file, since they are referring to the same thing. When the class is constructed, these three properties are defined as having values of None. However, as part of the KV Language parsing process, Kivy applies the styling found in orkiv.kv and overwrites those None values with the three values we specified in the previous example.

So we have widgets that are named by ids in our KV Language file that are being assigned to properties by the same KV Language file that are defined in the file. Got that? The upshot of this slightly convoluted pipeline is that we can now access those values inside the login method on our class:


    def login(self):

If you run the code now, you should see the contents of the login form boxes displayed on the console when you click the Login button.

Choosing client libraries

Let’s take a break from programming and talk about something that has been overlooked in every programming textbook and tutorial I have ever read: How the hell do you figure out how to do what you need to do?

The short answer, as with every question asked in the last decade, is “Search Google!” (or rather, a search engine that doesn’t spy on you, such as or Duck Duck Go). That always brings out the more salient question, “what do I search for?”.

If you’ve recently started learning to program, you might be under the impression that programming is mostly about connecting loops, conditionals and data structures into some meaningful representation of an algorithm or design pattern. That’s certainly a major part of the job, but often, programming involves reusing existing code and connecting it. Software development is often more like building a lego set where you get to use a variety of prefabricated bricks that do almost exactly what you need, and then using contact cement to glue on some custom-built parts that don’t come with the lego set and can’t be found on store shelves.

Anyway, at this point we have a login form that we can enter details in and do something when the button is clicked. But we aren’t doing what we want to do, which is to display a buddy list for the given XMPP account. How can we do that?

Well, one option might be to read through the Jabber Protocol Specification and implement all the Jabber commands one by one. But that sounds like a lot of work. The absolutely most important attribute in a good programmer is laziness. This means spending hours to automate boring things so you never have to do them again. It also means spending extra time now to write your code in such a way that you or a coworker can reuse it in the future. Finally, it means taking advantage of other people’s work so you don’t have to redo it.

Most common tasks have been collected into what are called “libraries”. Kivy itself is a sort of library, a library for creating kick-ass graphical interfaces. Often when faced with a “how do I do this?” question, the next question should be “Are there any existing client libraries that I can use?” Imagine if you had to manually set the value of each pixel on the screen in order to render a button or textbox, and then process individual keypresses directly to find out what was in a text input box!

Before I started writing this tutorial, I wanted to make sure there was a client library I could use to connect to Jabber. I did a web search and found several options, best summarized by this question on Stack Overflow. Stack overflow is a great place to search for answers; if you can’t find what you are looking for, you can even ask the question yourself!

If a web search yields a nice collection of client libraries that might solve your problem, the next question is, “which one do I use?” The answer is to visit the home pages for each of the libraries and ask yourself questions like these:

  • Is the license compatible with the license I want to use for my application?
  • (If not open source) How much does it cost to license the library?
  • (If open source) Does the source code for the library look well maintained and easy to read?
  • Does the library appear to be actively developed and has there been a recent release?
  • Is there an active user community talking about the library?
  • Does the library appear to have useful (readable, up-to-date, complete) documentation?
  • What avenues of support do I have if I have trouble?
  • (If Python) Does it boast Python 3 support?

After some amount of research, I ended up choosing Sleek XMPP as it seems to have a modern, usable application programmer interface, reasonable source code and documentation, and a permissive license.

At this point, you’ll want to install SleekXMPP and it’s one dependency. Make sure the virtualenv is active and then issue the following command:

pip install sleekxmpp dnspython

Figuring out how to use a client library

The next step is making yourself familiar with the client library so you know what functions and methods to call to create the desired behavior. This depends entirely on the documentation for the library. I personally like to start coding as soon as possible and see what breaks. Then I refer to the documentation and figure out why it broke and evaluate how it needs to change. In the case of SleekXMPP I started exploring the documentation until I could answer the question, “What is the simplest possible command-line application I can use to retrieve a buddy list?”. This is it:


import sleekxmpp, sys

xmpp = sleekxmpp.ClientXMPP(sys.argv[1], sys.argv[2])


This script isn’t part of orkiv, it’s just some playing around I did before trying to integrate this collection of method calls into Orkiv. It took me about 20 minutes to come up with these few lines of code, mostly because the SleekXMPP documentation is a little rougher around the edges than I anticipated. I first implemented a couple of the tutorials in the Quickstart and got them working. However, the examples seem to use a verbose inheritance structure that seems quite unnecessary to me. So I tried to extract the guts into the procedural example you see above.

I do my testing inside a running Python shell — just type python and you can start entering python commands right into the interpreter. I personally use IPython as much as possible, because its shell is so much nicer to use than the standard one. At first, my call to get_roster() was returning an error; this was because I hadn’t noticed, in dissecting the inheritance structure, that I had to call connect() first! However, after my trial and error phase were completed, I came up with the above code, which I saved as and tested using python orkiv/ password. I tested it with a throw-away Google account and my own personal jabber server. Works like a charm!

The script itself first imports a couple modules and creates a ClientXMPP object, passing in the username (in the form “username@server.tld”) and passwords from the command line. Then it calls several methods on this object to do some jabbery stuff. Then I output the value of the roster (“buddy list”), and disconnect.

Printing a buddy list on login button click

We could just copy the code above into the login() method and modify it to use the jabber id and password we got from the form. However, that would be rather short-sighted. We know we’re going to need to keep this ClientXMPP object around longer than a single button click, and indeed, longer than the lifetime of the login form. So instead, lets add a method to the Orkiv application object itself:


from sleekxmpp import ClientXMPP  # at the top of the file

class Orkiv(App):
    def connect_to_jabber(self, jabber_id, password):
        self.xmpp = ClientXMPP(jabber_id, password)

That’s a pretty simple method that creates an xmpp attribute on the app class and runs the boilerplate code for connecting to jabber, as we discovered in the script above. Of course, this method won’t actually do anything if we don’t call it from somewhere. The obvious place to do that, of course is when we click the login button. The correct thing to do will be to connect to jabber and then render a buddy list in the window, but we’re running out of space, so let’s just print it to the console:


def login(self):
    jabber_id = self.username_box.text + "@" + self.server_box.text
    password = self.password_box.text

    app = Orkiv.get_running_app()
    app.connect_to_jabber(jabber_id, password)

Once again, the method is quite simple. We first grab the jabber id and password from the form box, being careful to concatenate the username and server to generate the jabber id. The next line, where we get the running app may require some explanation. We are calling a function on the Orkiv class itself. Remember, a class describes an object, so we aren’t talking to an instance of that object here, just to the class. When a method is meant to be called on a class instead of an instance of that class, it is called a static method. In this case, the static method happens to return an instance of the class: the currently running app. Normally, there is only ever one running app in a Kivy program. In fact, you’d have to be both foolish and audacious to get more than one.

The other slightly tricky thing about this line is that we have not defined any get_running_app method on the Orkiv class. In fact, we only have one method, connect_to_jabber. But remember that Orkiv inherits functionality from the App, and indeed, App has a get_running_app static method. That’s what we’re calling here.

Once we have access to the active app object, it’s easy to print the roster and disconnect. Obviously, it wouldn’t make sense to disconnect immediately after login in a completed jabber client. However, if you don’t disconnect and test this, the program won’t stop running when you close the window; it leaves the xmpp object hooked up in the background trying to do the kind of stuff that jabber clients do. When I tried it, I had to force kill the process with kill -9.

It is common, when coding, to do temporary things like this to test the program in its current state. We know we’ll remove that line in part 4, but… well, truth be told, part 4 hasn’t been written yet! In part 4, we’ll deal with some annoyances with this form, like the fact that we can’t tab between input fields, that we have no idea what happens if we provide incorrect login details, and that pesky problem of the jabber staying alive after we closed the window.

Monetary feedback

If you liked the tutorial and would like to see similar work published in the future, please support me. I hope to one day reduce my working hours at my day job to have more time to devote to open source development and technical writing. If you think this article was valuable enough that you would have paid for it, please consider supporting me in one or more of the following ways:

I’d particularly like to advertise Gittip, not for my own financial gain, but for everyone. I think a world where people are able to use gittip for their primary source of income is a world worth striving for. Even if you don’t choose to tip me, consider tipping someone, or if you are a producer of knowledge or art, market your own products and services through the generosity system.

Finally, if you aren’t in the mood or financial position to help fund this work, at least share it on your favorite social platforms!

Creating an Application in Kivy: Part 2

This article continues the tutorial we started in Part 1. In the first part, we set up a Kivy project and developed a very basic Kivy application. We also discussed version control to aid in project management. In this part, we’ll be designing an actual user interface for a Jabber client and begin to implement it in the KV language.

Make sure you have completed part 1, or if you want to skip the preliminaries, you can clone the end_part_one tag of the Orkiv git repository and start from there. It’s probably a good idea to name a new branch for your working changes so your master branch doesn’t diverge from my upstream repository. Remember to activate the virtualenv you created in Part 1 (or create one if you’re starting from the git clone.)

git clone
git checkout end_part_one
git checkout -b working_changes
source venv/bin/activate

Table Of Contents

Here are links to other parts of the tutorial. I’m sorry for the navigation faux pas; blogs are not the best interface for multi-part articles.

  1. Part 1: Introduction to Kivy
  2. Part 2: Creating a form
  3. Part 3: Interacting with widgets and the user
  4. Part 4: Code and Interface Improvements
  5. Part 5: Rendering a Buddy List
  6. Part 6: ListView Interaction
  7. Part 7: Receiving messages and interface fixes
  8. Part 8: Width based layout
  9. Part 9: Deploying your Kivy application

Interface Design

In general, before developing a user interface, it is a good idea to know what you want it to look like. I see this project having three main views. When the user first opens the application, they’ll see an Account Details screen to provide their jabber server and login credentials. We won’t bother with saving these details since this tutorial series is focused on Kivy interface development, not persistence. Once they have logged in, the other two views are a Buddy List and the individual Chat Window.

I would like to develop the app to show the buddy list and chat windows side by side if the screen is large enough (eg: a laptop screen or large tablet in horizontal orientation), but only one window at a time on small screens. It is very important to evaluate screen size when developing cross platform applications; it is generally not desirable or feasible to render the same view on large monitors and small phones. We’ll look at this feature in later tutorials, but knowing that we want to plan for it now will affect how we implement our design.

All of these windows are pretty simple. In this second part, we will focus on the account details screen. It will be a simple form with labels on the left and fields for entering the various details on the right. The fields covered will include server, username, and password. Below these fields will be a Login button. Normally I’d sketch the interface on a piece of paper, but since this looks like every other Jabber client on the market, I don’t think it’s necessary.

The Account Details Form Widget

In Kivy, virtually every object that gets displayed on the screen is a widget. Just a few examples include:

  • The label we rendered in the first tutorial
  • The text input fields and buttons we’ll render in this tutorial
  • Layout classes that contain other widgets and decide where they should be displayed
  • Complicated tree views such as file pickers
  • Movie and photo renderers
  • Tabbed boxes that display different widgets depending on the selected tab

It is easy to make custom widgets, and to access all widgets, whether custom or otherwise, from KV language files. We’ll be creating a new widget to contain our entire Account Details form. Start by adding a new import and class to


from kivy.uix.boxlayout import BoxLayout

class AccountDetailsForm(BoxLayout):

Running the code with this addition won’t change anything in the output, since the newly created widget hasn’t been added to the root window. However, there are a few things we need to discuss before we change the KV language file to use this widget. You might be asking yourself why we created a new widget instead of adding a BoxLayout widget (whatever that is!) directly to the root of the KV language file orkiv.kv. While it would have been trivial to do this, it would have made putting a new widget (such as the Buddy List) on the root screen more difficult. Further, when it comes time to attach events to the Login button, we can make it a method of this new class, where it makes the most sense.

The BoxLayout is a very simple widget that simply takes the available space and places all the child widgets in it from left to right or top to bottom. By default, each widget gets an equal amount of space, but it’s also possible to make certain widgets have specific sizes or percentages of space or to expand to fill available area.

BoxLayout is one of several kinds of layouts available in Kivy. A layout is simply a container widget that holds other widgets and knows how to position those child widgets in a specific pattern. We’ll be seeing a GridLayout shortly. You can read about other Kivy layouts in the Kivy API Reference.

Let’s edit orkiv.kv to render this new widget as the child form instead of the label we used before. We’ll also add a couple labels to the AccountDetailsForm class so you can see the relationship between root widgets and classes in the KV Language:



        text: 'Hello World'
        text: 'Another World'

There’s a couple things going on here. The root widget of the Orkiv app is defined as a AccountDetailsForm. This is followed by a colon in case we wanted to add other child widgets to the object, but in this case, it’s just followed by a blank line. Then we define the structure of the child widgets of the AccountDetailsForm class itself. We know it’s a class and not a root widget because the class name is surrounded in angle brackets (< and >). Further, one app can only have one root widget. We just defined that root to be pointing at a single AccountDetailsForm. However, note that a class can be styled once and added in more than one place. Just as our AccountDetailsForm has two labels, it would be possible (though silly, from an interface perspective) to create a container widget that contains two AccountDetailsForms. The point is, an AccountDetailsForm, once its layout has been defined, can be used just like any of the built-in widgets supplied with Kivy.

If you run python orkiv now, it will render the two labels side by side, each taking a full half the window. Note that there are actually three widgets being rendered; first, the AccountDetailsForm (which is a BoxLayout by inheritance) is rendered to fill the whole screen, and then it lays out the two labels as child widgets.

However, that’s not the AccountDetailsForm we were looking for! Let’s create our first nontrivial Kivy Language class. Replace the class in your orkiv.kv with the following:


    orientation: "vertical"
        cols: 2
            text: "Server"
            text: "Username"
            text: "Password"
            password: True
        text: "Login"

It’s time to discuss just how the Kivy language lays things out. In my mind, it uses a box model similar to HTML, except instead of ugly HTML tags, indentation is used to specify what widgets go inside other widgets. Also, unlike HTML, style information is included in the .kv file instead of an external .css file. Though it’s not a hard and fast rule, style information (called properties in Kivy) typically begins with a lowercase letter, while child widgets start with a capital.

Look at the first level of indentation under the <AccountDetailsForm> declaration. There are three items; orientation, GridLayout, and Button. The former counts as “style information”. Remember that the AccountDetailsForm class extends BoxLayout. One of the attributes on BoxLayout is “orientation”; we are telling BoxLayout here that we want a vertical layout.

This vertical box layout then contains two widgets, a GridLayout and a Button. The GridLayout spaces all it’s children equally. We just have to tell it that there are 2 columns (the cols property) and then start adding our objects, which are displayed from left to right and wrap to the next row in the grid after every two widgets. We add Labels and TextInputs. Each label has a text property that we set using a further level of indent. The TextInput objects don’t require any extra properties except the password.

Later, we’ll have to give these objects some identifiers so we can refer to them in code. For this initial prototyping stage, we can start with the bare minimum. If we render the above example, we end up with a recognizable, but rather ugly form:


Restricting sizes

Let’s try to make the form a little less ugly:


    orientation: "vertical"
    height: "200dp"
    size_hint_y: None
        cols: 2
        row_default_height: "40dp"
        row_force_default: True
        spacing: "10dp"
        padding: "10dp"
            text: "Server"
            text: "Username"
            text: "Password"
            password: True
        size_hint_y: None
        height: "40dp"
        text: "Login"

All we’ve done here is add some styling information to make the layout a little more friendly. This can be complicated as we want the app to look good on a variety of devices at a variety of resolutions and screen sizes. The main thing is to ensure all the widgets have a known height. As you might guess, this can be accomplished by adding a height property to each of the widgets. However, doing this alone will not work because BoxLayout likes to think of itself as in charge of deciding what size a widget should be. Without any styling, heights in a vertical BoxLayout are calculated as the number of widgets divided by the available screen space. However, it’s possible to tell BoxLayout to make certain widgets take a higher percentage of available space by giving it a size_hint_y attribute, which should be a float and defaults to 1.0. Unfortunately, for textboxes and buttons, percentages don’t really make a lot of sense, since we have no idea what size the window or screen of a particular advice is going to be, but we do know we want them to be about the same height on each screen.

So in addition to setting the height attribute, we also have to set size_hint_y to None for those widgets to prevent BoxLayout from ignoring the height property and laying things out by percentages instead.

You’ll also note that we are specifying the heights using strings that end in the suffix “dp”. It’s possible to provide integer values here, which would be interpreted as the number of pixels high the button is. However, due to the massive variance in screen resolutions on modern devices, it’s not really feasible to use pixels as a measurement. A login button that is 40 pixels high and looks good on a desktop monitor would look very small, indeed, on a “retina” display tablet.

Therefore, Kivy provides us with the concept of “display pixels”; hence the “dp” in the strings. Display pixels should be about the same size on every device; on a standard desktop monitor they generally map to a single pixel, but on higher density displays, they will be multiplied by a scaling factor. There are other metric properties such as cm or in that you can use, but I generally find it most convenient to think in display pixels.

Note also that instead of supplying heights for each of the Label and TextInput widgets inside the grid layout, we cheated and used the row_default_height attribute so all rows have the same height. For this to work, you also have to set row_force_default to True.

Finally we added spacing and padding properties to the GridLayout to add a 10dp space between child widgets and a “frame” around the whole GridLayout as well. If we run this example, it looks like this:


There’s one more thing I’d like to do before ending this part of the tutorial. As you can see above, the form is showing up at the bottom of the window, no matter what size the window is. That might look a bit bizarre on a tablet or even phone screen. It would be better if the entire form was anchored to the top of the window.

As an exercise, take a few moments to experiment (remember to use a different git branch!) and see if you can figure out how to move the form to the top by yourself. The next paragraph contains some hints if you get stuck, and the working code is linked after that. (I’m not about to tell you not to cheat, since it really depends what your personal goals are in reading this tutorial.)

There are probably multiple ways to do this, and I’m not even certain my solution is the best one. But I suggest making the AccountDetailsForm into an AnchorLayout and anchor a child BoxLayout to the top of the form. Note that you’ll have to change both files to make this happen.

If you’re still confused, have a look at the full changeset at the changeset on github.

That’s it for part 2 of this tutorial, which focused on laying out widgets in the KV Language. In part 3, we’ll figure out how to log into an XMPP library and render a buddy list. Note that I don’t actually know how to do this, so we’ll have to figure it out together!

Monetary feedback

When I wrote this tutorial, I didn’t expect it to be big or popular enough to publish as a book. However, the series caught O’Reilly’s eye, and I have since written an entire book on Kivy. If you want to support me and learn more about Kivy, you and I both will be delighted if you buy it.

If you like the tutorial and would like to see similar work published in the future, this isn’t the only way to support me. I hope to one day reduce my working hours at my day job to have more time to devote to open source development and technical writing. If you think this article was valuable enough that you would have paid for it, please consider thanking me in one or more of the following ways:

If you aren’t in the mood or financial position to help fund this work, at least share it on your favorite social platforms!

Creating an Application in Kivy: Part 1

This is the first in what I expect to be a series of tutorials on creating user interfaces in Kivy. Kivy is a cross platform user interface framework that allows us to write applications in Python that run on various desktop operating systems, Android, and IOS.

I’ve wanted to write a tutorial on Kivy since hacking on Python 3 support during the dev sprints at Pycon 2013. My goal is to create a useful application that runs on multiple devices and highlights use of the KV Language to design user interfaces. I also want this multi-part series to describe end-to-end how to develop, maintain, and deploy a Kivy application. I intend it to be a model for newcomers to Kivy and even Python to develop their own cross platform or mobile applications in Python. Thus, it doesn’t just include code, but also deployment instructions and information on how to use the git version control system for basic history management.

Therefore, this tutorial series is written at a more basic level than a lot of my technical articles. My intended audience is new programmers who have some basic Python experience; perhaps having read The Python Tutorial and Learn Python The Hard Way, but possibly not the beginner-intermediate topics covered in my book, Python 3 Object Oriented Programming.

Having decided to write a tutorial, I needed to decide what kind of application to develop. This actually took quite a bit of thought. I decided on a Jabber client, as it has a user interface with reasonable complexity, and I am hoping that most of the difficult bits can be abstracted away into the SleekXMPP library. Finally, I had to settle on a name for the app; I chose Orkiv. I do not know why.

Table Of Contents

A blog isn’t the best platform for publishing a multi-part tutorial. I’ll include a Table Of Contents section in each part with references to all the other parts. Hopefully I’ll even keep it up to date!

  1. Part 1: Introduction to Kivy
  2. Part 2: Creating a Form
  3. Part 3: Handling Events
  4. Part 4: Code and Interface Improvements
  5. Part 5: Rendering a Buddy List
  6. Part 6: ListView Interaction
  7. Part 7: Receiving messages and interface fixes
  8. Part 8: Width based layout
  9. Part 9: Deploying your Kivy application


Start by installing the following pre-requisites using standard operating system tools.

Python is the programming language and interpreter that Kivy programs are written in. Git is a version control system that we will use to track changes to our code. Virtualenv is a tool for creating isolated Python environments. Pip is an installer for installing python packages, in this case into the isolated virtualenv.

Note: Use of git is optional if you are more interested in learning to code than learning to manage a project. You are also welcome to use another version control system of your choice. At the level we will be working, the commands are virtually interchangeable.

Setting up the environment

Run the following commands in a terminal. (Note this tutorial was written using Arch Linux, and will probably work flawlessly on MacOS and other Linux distributions. However, you may need to do some experimenting to make Windows cooperate).

mkdir orkiv
cd orkiv
git init
virtualenv -p python2.7 venv
echo venv >> .gitignore
echo "*.pyc" >> .gitignore
git add .gitignore
git commit -m "Create .gitignore file. Ignores compiled python files and venv."
source venv/bin/activate

We’re creating a directory to hold our project and then initialize a git repository in there. We next create a virtualenv in a folder named venv. This folder will hold the isolated python files so that you can interact with Kivy without adding cruft to your system Python. I highly recommend creating a separate virtualenv for every project you work on.

Next, we set up a .gitignore file that tells git not to track certain files in our repository; in this instance all compiled python files, which end in .pyc, and the virtualenv directory we just created. We commit the changes to this file as our first commit in the git repository.

Finally, we “turn on” the virtualenv by sourcing its activate script. This essentially tells our shell to “use the isolated python for this project instead of system python”. When you are done working on this project, you should enter the command deactivate. When you come back to the project in the future, reenter the source venv/bin/activate command to turn on the isolated environment.

Note: If you maintain a lot of virtualenvs in a lot of different projects, as I do, you may be interested in a small script I wrote to facilitate switching between them.

Kivy Dependencies

Kivy depends on several Python libraries. Unfortunately, it does not have a setuptools-enabled to automatically install these dependencies into our virtualenv, so we have to do a little work ourselves. This takes a while, but if you copy paste these commands into your terminal, you should get lucky.

pip install cython
pip install pygame

Sadly, on Arch Linux, the last command, for pygame fails. I suspect it works fine on less bleeding edge operating systems, however, if you encounter an error about linux/videodev.h not existing, applying the Arch Linux patch to pygame may get you to the next step.

wget -O pygame-v4l.patch
tar xf pygame-1.9.1release.tar.gz
cd pygame-1.9.1release/
patch -Np1 -i ../pygame-v4l.patch
python install
cd ..
rm pygame* -r

And now, you should finally be ready to install Kivy itself: This will take a while, so grab a smoothie while it runs:

pip install kivy
python -c 'import kivy'

The latter command should output the kivy version (I’m working with 1.7.1). If it exits without failure, then you have successfully installed Kivy!

Now let’s create a basic Kivy app

Create a directory to hold the application code:

mkdir orkiv

This directory will contain your Python and Kivy source files. Our goal is to be able to always create a zipfile from this directory and be able to run it using python As long as the required dependencies are installed on the target system (as described above), the program should run. It will therefore be nice and self-contained.

There is a relatively unknown feature of recent versions of Python to support this. If a directory or zipfile contains a, that module will be executed if python is called with that directory or zipfile as an argument. First, create a file inside the new orkiv directory named Create a simple “hello world” in this file to test that
it’s working:


print("hello world!")

Now from the parent directory, run the command python orkiv. If you want to test it with a zipfile, try this:

cd orkiv
zip ../ *
cd ..

It is possible to code Kivy applications in pure Python, but in my opinion, it is much better to use the amazing KV Language to do layouts. The basic approach is to have a Python file (in our case above) that contains the logic for the application, and a KV Language file that contains the layout information. The KV Language is very similar to Python and you can learn it as you go.

Lets start by removing the print statement from our and replacing it with the most basic possible Kivy application:


from import App

class Orkiv(App):


This simply imports a Kivy App class and creates a subclass of it using Python’s notoriously simple inheritance syntax. Inheritance is a useful feature of Object Oriented Programming that basically means that a class can be defined that has all the functionality of the parent class. In this case, since we didn’t add anything to the subclass, that’s ALL it has. However, the true beauty of inheritance is that we can add new properties and methods (functions attached to objects) to the subclass or even change the functionality that comes with the parent class (App). The best part is, we don’t really have to know what is going on inside the App, and can assume the Kivy devs know what they are doing.

It doesn’t even add anything to the subclass! Then it instantiates an instance of that subclass and calls the run() method on the newly created object.

If you run python orkiv with the new code saved, you’ll see an empty window pop up.

As far as boilerplate goes, that’s pretty damn concise, don’t you think? The amazing thing is that we can start laying out KV Language widgets in a separate file without touching this boilerplate at all! Don’t believe me? Try saving the following as orkiv/orkiv.kv:


    text: "hello world"

Now if you run python orkiv, you should see the “hello world” label centered in the window that pops up. It’s almost like magic, and if you’re like me, you’re probably wondering how that’s even possible.

When you create a subclass of a, it introspects the name of the new class (we named it Orkiv). Then it looks for a file in the same directory that follows these rules:

  1. Ends with the .kv extension
  2. Starts with the name of the class converted to lowercase and with any
    trailing App stripped.

The Kivy documentation would have named the class OrkivApp and still used the orkiv.kv filename. Personally, I don’t see the redundant need to add App to the class name, since the inheritance structure clearly indicates that Orkiv is a App.

We’ll be working with the Kivy Language a lot as we proceed through each part of this tutorial. You’ll soon see that it’s possible to do more, a lot more, than add a label to a window!

A note on version control

At this point, you’ve created a logical related set of changes that are in a working state. I want to encourage you to experiment with these files, maybe change the contents of the label, try a different application and KV Language filename, or see if you can figure out how to group two labels into a single layout. But before doing that, you should record this known state that your repository is currently in so it’s easy to get back to. That way, you can be free to explore without fear of getting completely lost; you’ll always have a path straight back to your current state. You can do that from the command line using git:

git add orkiv/
git commit -m "A basic Kivy boiler plate"

You just made a commit on the master branch in git. First you listed the changes you wanted to include in the commit (the entirety of every file in the new orkiv directory), then you told git to record the current state of those files forever. It is generally recommended that you only save consistent, known-to-be-working state on the master branch. For the purposes of this tutorial, I suggest that you only save the code you copied from the tutorial to the master branch, and do your other development on other branches.

Are you confused by what a branch is, exactly? Think of it like walking down a forest path in a national park. You are following signs for a marked trail; that’s this tutorial. As you walk, you see things that you want to remember, so you take a photo. That’s like making a commit on the master branch. However, you also see side paths that you would like to explore on your own. You can go down that path as far as you want, or even take other random paths without fear of getting lost. You can even take photos on those paths, knowing they won’t get mixed in with the photos from the main trail. Then when you want to return to the point where you left the main trail, you can magically teleport back to it (or indeed, to any of the other branches you walked down in your exploration).

You probably won’t be doing it for this tutorial, but the most import aspect of version control is that if you are in unmarked forest rather than a national park, you can walk down all the paths and decide which one you’re going to choose as the main path. You can even merge paths back into each other so that the photos (code commits) taken on each of them end up in the same final presentation.

Enough digressing! For your purposes, the first thing you should do is create a new branch in git:

git checkout -b my_exploration

You are now on a new branch named my_exploration (you can call each branch whatever you want, of course) that is exactly the same as the master branch as you last saw it. But you can make changes on that branch to your heart’s content; you can add and commit them as above if you want to remember them for later. When you’re ready to come back to the tutorial, you can use this command to return to the current state of the master branch:

git checkout master

From there, you could continue with the next part of the tutorial, or you could create a new branch and explore in a different direction.

Browsing the examples

I am maintaining my own version of the code developed in this tutorial at However, it’s not likely to be the same as your repository, since I’m not making commits at the same time that I’m suggesting you make commits. Instead, my master branch contains a separate commit for each example in the tutorial. I also create git tags for each part of the tutorial so it’s fairly easy to see from commit history what was covered in each part. If you browse the Commit History you can see each example and how it evolved from top to bottom. You can view the list of tags here.

Monetary feedback

When I wrote this tutorial, I didn’t expect it to be big or popular enough to publish as a book. However, the series caught O’Reilly’s eye, and I have since written an entire book on Kivy. If you want to support me and learn more about Kivy, you and I both will be delighted if you buy it.

If you like the tutorial and would like to see similar work published in the future, this isn’t the only way to support me. I hope to one day reduce my working hours at my day job to have more time to devote to open source development and technical writing. If you think this article was valuable enough that you would have paid for it, please consider thanking me in one or more of the following ways:

If you aren’t in the mood or financial position to help fund this work, at least share it on your favorite social platforms!

Next Year: addressing the more subtle sexism at Pycon

From a gender equality point of view, I’d call Pycon 2013 a success, though perhaps a better word is “progress”. The gender ratio apparently doubled to 20% this year. If that continues (depending if it’s a constant, linear, or quadratic curve) we could be at parity in as little as two to three years.

Another indicator of forward momentum is that women this year were able to behave, to use a sexist term, “like women,” without fear of reprisal. That is to say, I saw makeup, heels, and skirts, and they did not seem out of place. This is not to suggest that women should or must dress up to attend conferences; the traditional vendorware is equally acceptable for all genders. However, it is progress that more women felt they had a choice in the matter and did not feel an obligation hide their physical differences. I think the fact that there was more variety among the male dress styles is also a sign of success.

The worst charges coming out of Pycon 2013 were the use of inappropriate jokes. To the best of my knowledge, there were no reports of women being harassed, assaulted, or groped during the conference. I’m not aware that this has been an issue at past Pycons either, but I think it’s a sign that the Python community is better behaved in this regard than some of her sister tech conferences.

So all in all, while it wasn’t completely successful, Pycon 2013 was a terrific step on the road to eliminating sexism and creating gender equality. Let’s make next year an equal sized step. Here are a few topics I think we, as a community, can work on to engender further progress.

I’m going to start with a couple links. Ruth Burr wrote a terrific essay titled Things You Think Aren’t Sexist, But Really Are a couple weeks ago. In summary: Men, you are instructed to go to conferences to network and interact, not to date or hook up.

Yes, you might meet the love of your life at Pycon, but don’t expect, intend, or plan for that to happen (at PyCon or anywhere). Behave professionally, and consider each woman you meet for her knowledge and intelligence, not her figure or her marital status, just as you would when interacting with a male.

Ned Batchelder, with his amazing talent for understanding and explaining problems wrote another great article on the root issues. Summarized, he says friction is inevitable, and that education is better than shunning when people make mistakes.

I started planning this article while attending Pycon this year. I had to scrap those plans after the so-memed “donglegate” fiasco. I don’t have anything to add to that discussion, but as Ned illustrated, there were many many instances of similarly inappropriate comments at Pycon. I myself made such a joke, most of my friends did so, I overheard a conference organizer say something inappropriate. This is not sexism per se, but sexual and other potentially offensive comments need to be reduced. Comments laced with sexual innuendo do not belong in a professional or a family setting, and Pycon is intended to be both.

Let’s start with interation between the genders. In her article, Ruth Burr mentioned that women can feel awkward when they interact with men because the men assume they are flirting rather than interested in the topic at hand. Many men see cleavage and assume the speaker can’t possibly know as much as them about whatever topic that is. Some girls avoid interacting with men because of this awkward sensation, and if they do, the interactions are tainted.

I had a related problem. While I comfortably talked to men of varying skill levels at Pycon, I felt uncomfortable addressing women because I was afraid of sending some vibe that I was being flirtatious. So I tended to ignore the female attendees. This is unfortunate for everyone who missed out on that potential conversation. Pycon 2014 needs to increase the interaction between the genders, not just the attendance ratios. Ladies, talk to the shy guys, they need to be taught that you aren’t that intimidating. Guys, talk to the women, they need to learn that we are interested in what they have to say about tech, and not their figures. As it stands, only the sexist guys are interacting with the women, and it makes us all look bad.

The gender ratio really fell during the developer sprints. I don’t think there were any female sprint leaders presenting projects to hack on. Worse, I’d estimate between one and two percent of the sprint attendees were women. This is a huge area for improvement. To the various diversity groups out there, please encourage your members to stay an extra day or two and attend the Pycon dev sprints. Get them involved with Open Hatch if they are unsure how to contribute to open source projects. Sprint leaders, make sure female attendees are welcome, especially if they are new coders (indeed, make all new coders welcome).

I noticed a lot of Impostor syndrome among the female attendees and speakers. Programming really is easy. The fact that you enjoy it and find it quite simple is not a sign that you don’t know the “hard stuff” and therefore you’re not a “real programmer.” Quite the reverse, in fact. It’s not necessary to apologize for your lack of knowledge if you’ve been invited to do a talk or are about to join an open source project for the first time. Find ways to build your confidence (contributing to open source and getting feedback is a great start), and start believing in your skills. Even if you don’t believe it yourself, try to project confidence in your coding abilities; it will send a much more effective signal that women are capable and here to stay. Don’t worry if you over-present yourself; faking your way through it is a great way to find out that you’re actually better than you thought!

I’d like to close with an admonishment to those people who open their articles on sexism with a discussion of their gender. These usually take one of two forms: the disclaimer and the shocker. The disclaimer is most often used by men and sounds like, “I am a privileged white male so I don’t understand what it’s like for women, but I still think I have something valid to say on this topic”. The shocker is used by both genders and sounds like, “I am a man/woman, so you’re going to be amazed that my opinion on this topic is different from other members of my gender.” Yes, it is useful to state your bias and frame of reference. However, be cautious that your purpose in doing so is to remove distortion from the lens you are applying to the discussion, not to add to it.

And now, feel free to analyze my bias in this article. I am a privileged white male from a blue-collar family. I’ve had many amazing opportunities in the tech industry. I have very little experience as the target of discrimination, outside my mental illness. My interest in feminist issues comes from my sister’s master’s degree on the subject; I proofread most of her undergraduate and graduate level essays, and gained a relatively deep understanding of the topic. I acknowledge that I am a racist, sexist jerk by culture and conditioning. Sometimes I forget to compensate for that. I find it exceptionally easy to overlook the patriarchy when it’s doing me favors, and I will never be as keenly aware of its negative impact as someone who is directly experiencing it every day.

Guido Van Rossum Should Retire (and focus on python)

At the two previous Pycons I’ve attended (2009 and 2012), Guido Van Rossum’s keynotes sounded bored and uninterested, even though the content was meaningful. I was actually wondering if this would be the year that he would step down from BDFL of Python. Thankfully, I was dead wrong.

Instead, he presented a highly technical and very exciting addition to the Python language. Alfredo told me this started when he took a month off between stepping down at Google and starting at DropBox. Now, when normal people take a month off, they relax or travel or visit friends and family. Not our BDFL. He writes a callback-free asynchronous event loop API and reference implementation that is expected to massively alleviate Python’s oft-maligned lack of a consistent, unhackish concurrency solution.

Let’s have more of that. What if Mr. Van Rossum could hack on Python full time? Would we see quantum progress in Python every month?

Anyone who knows about the Gittip project likely thinks they can guess where this is going. We, the people, can each tip our BDFL a few cents or dollars per week so he can focus on whatever he deems worthy. It’s safe to assume that a man who spends his vacation time drafting a new Python library would choose to work on Python full time if we funded him.

This plan is great, and I actually think that Guido could easily earn enough to quit his day job if he endorsed Gittip and invited individuals to tip him. But I’d like to discuss a different plan: Not individuals, but companies should tip Guido the maximum gittip amount as a sort of “partial salary”. At $1248 per year, most companies wouldn’t even notice this expense, and they would get a better programming language and standard library in return. The rate of accelerated development would be even higher if each of these companies chose to invest an entire salary, split between a hundred Python core and library developers. If a hundred companies chose to do this, those hundred people could work on Python full time. The language and library would improve so vastly and so rapidly that the return on investment for each of those companies would be far greater than if they had paid that same salary to a single developer working on their in-house product, full time.

It might take some convincing to justify such a strategy to these corporations. Companies tend to like to know what is happening to their money, and simply throwing a hefty developer salary at Gittip would be hard to justify. Obviously “goodwill” could support some of it, in the same way that so many companies sponsored Pycon in exchange for exposure.

Cutthroat CEOs should perhaps consider not just the value that having Guido working exclusively on Python is, but also the cost of having him work for the competition. I’m sure CEO Aaron Levie was a little nervous when he found out that the first and greatest Python programmer of all time had recently hired on at a major competitor. Perhaps can’t afford to steal Guido from Dropbox, but if all the companies currently involved in cloud storage were to tip Guido $24 per week on Gittip, this incredible programmer could be working on an open source product that directly and indirectly benefits their company rather than improving the competing product on a full-time basis.

Most of the arguments that Gittip will fail are based on the premise that not enough money can be injected into the platform to sustain full time development by open source programmers. However, if an open and caring relationship can be built such that the corporate world is also funding the system, I think it can become extremely successful. Everyone will benefit: Open source projects will improve at a rapid pace. Exceptional developers will get to pursue their passions. End users will get better products. The overall level of happiness in the world will be higher.

I would like to see a world where brilliant young software engineers are not risking their mental health (and consequently, their lives) on startup ideas in the hopes of being bought out for a few billion dollars. I would like to see a world where those engineers are not working for large corporations that have neither their employees nor their end users (but rather, their stockholders and advertisers) interests at heart. I would like to see a world where those developers can choose to invest their passion in open source products that will change the world.

Excluding tests with py.test 2.3.4 using -k selection

When I use py.test, I often rely on the -k switch to swiftly select the test I want to run. Instead of having to type the full module, class, and test path as is required with unittest and nose, I can just type a few characters that uniquely match the name of the test.

For example, if I have a test file containing methods test_basic_clone and test_basic_clone_notes, I can run the latter test simply by calling py.test -k clone_no.

However, I often create multiple tests that have similar names. This can make it difficult to run just one test if the test name is a prefix of a longer test name. If I want to run just test_basic_clone, any substring will also be a substring of the test_basic_clone_notes test, and both tests are matched by -k.

Since pytest version 2.3.4, the -k keyword supports expressions. So I can build an expression like this:

py.test -k "basic_clone and not notes"

This selects all tests matching “basic_clone”, then excludes any containing the word “notes”. Thus, I run only the test I’m interested in without having to fix my crappy naming scheme. It’s more typing than is normally the case, but is still less cognitive load than trying to remember what module and class I’m editing and constructing a selector based on those attributes.

Gitifyhg is now awesome.

Gitifyhg is a git client for pushing to and pulling from Mercurial repositories. I described the first implementation, which used hg-git internally, last month. However, I found that it didn’t work as well in practice as my initial tests had indicated, and I morosely reverted to using hg directly.

While researching ways to improve the app, I stumbled across git-remote-hg by Felipe Contreras. It claimed to be a cure-all to the git-hg bridging problem that “just worked”. So I downloaded and tried it, but it didn’t live up to the author’s hype. While it could handle basic cloning, pushing to and pulling from the default branch, it failed for me when working with named upstream branches, something I have to do regularly in my day job. I submitted several issues and pull requests, most of which were ignored. The more deeply involved I became with the code, the more I felt a complete rewrite was in order.

I had some free time during the holiday season, and started my version of a git remote as an exercise, with no intent to create anything useful. To my surprise, something useful emerged. In fact, I believe gitifyhg is the most robust and functional git to hg client currently available. More importantly, it is eminently hackable code: well tested and fairly well documented. I hope this will make it easy to contribute to, and that my inbox will soon be full of pull requests.

This is the real deal. The best part is that you don’t have to learn any new commands. It’s just basic git with mercurial as a remote. The only command that has changed from normal git usage is clone:

pip install gitifyhg
git clone gitifyhg::
cd hg

By adding gitifyhg:: before the mercurial url, you can git clone most mercurial repositories. If you can’t, it’s a bug. Other complex repositories I have successfully cloned include py.test and pypy.

You can easily use gitifyhg in the fashion of git-svn. All named branches are available as remote branches. default maps to master. Other branches map to branches/<branchname>.

If you want to commit to the master branch, I suggest a workflow like this:

git clone gitifyhg::<any mercurial url>
cd repo_name
git checkout -b working  # make a local branch so master stays prestine
# hack and commit, hack and commit
git checkout master
git pull  # Any new commits that other people have added to upstream mercurial are now on master
git rebase master working  # rebase the working branch onto the end of master
git checkout master
git push

Working on a named mercurial branch, for example feature1, is easy:

git checkout --track origin/branches/feature1
git checkout -b working  # make a local branch so feature1 stays prestine for easy pulling and rebasing
# hack and commit, hack and commit
git checkout branches/feature1
git pull  # New commits from upstream on the feature1 branch
git rebase branches/feature1 working  # rebase the working branch onto the end of feature1
git checkout master
git push  #push your changes back to the upstream feature1 branch

It is even possible to create new named branches (assuming my_new_branch doesn’t exist yet in Mercurial):

git checkout -b "branches/my_new_branch"
# hack add commit
git push --set_upstream origin branches/my_new_branch

These basic workflows have been working flawlessly for me all week. In contrast to my previous attempts to use git to hg bridges, I have found it easier to use gitifyhg than to work in the mercurial commands that I have become expert with, but not used to, in the past year.

Gitify hg is not yet perfect. There are a few issues that still need to be ironed out. There are failing tests for most of these in the gitifyhg test suite if you would like to contribute with some low-hanging fruit:

  • Anonymous branches are dropped when cloned. Only the tip of a named branch is kept.
  • Tags can be cloned and pulled, but not pushed.
  • Bookmarks can be cloned and pushed, but not pulled reliably. I suspect this is related to the anonymous branch issue.

So give it a shot. Gitifyhg is just one easy_install gitifyhg away.

Opterator, revisited

A few years ago, I wrote a simple decorator that introspects a main() method signature and docstring to generate an option parser. I never really used it, mostly because back then, I wasn’t too keen on third party dependencies. Nowadays with distribute being maintained, well-documented, and working (plus I know how to use it properly), I no longer have this concern.

A friend recently linked me to the brilliantly designed docopt and reminded me of my interest in opterator. I revisited my code and decided it’s a pretty neat little design. So I ported it to Python 3. This took a matter of minutes, largely because I originally wrote it shortly after taking the pytest tutorial at Pycon 2009 and it was easy to find the failing code. It now supports Python 2.6, 2.7, and 3.3, according to tox.

I originally designed opterator to be a full replacement for optparse and friends. However, my main purpose for it now is to create quick and dirty command line applications, often for my personal use. These apps usually have a couple of options and it doesn’t seem worth the trouble of setting up optparse. Yet, mucking around with sys.argv is also annoying. Opterator minimizes the boilerplate. Check out this basic example:

from opterator import opterate                      

def main(filename, color='red', verbose=False):     
    print(filename, color, verbose)


with three lines of boilerplate code, a function can be turned into a command line program that can be called like so:

  $ python examples/ this_file
  this_file red False

or so:

  python examples/ this_file --color=blue
  this_file blue False

or even so:

  $ python examples/ --color=purple another_file --verbose
  another_file purple True

And you even get a not totally (but somewhat) useless helpfile:

  $ python examples/ -h
  Usage: [options] filename

  -h, --help            show this help message and exit
  -c COLOR, --color=COLOR
  -v, --verbose

Building a Python Kivy App in Android (Easier than it looks, but harder than it needs to be)

When I introduced Kivy a while back, I mentioned that I had not been able to deploy a Kivy app on Android. I’ve managed to do this now, using the VirtualBox image provided by the Python For Android project. Using this image was substantially less work than trying to figure out how to install and set up all the prerequisites under Arch Linux. So here’s how to do it:

First download the VirtualBox image from Google Drive. Sadly I cannot find an adequate wget command to download this. Shame on you, Google!

You may want to double check the documentation to see if a later image has been made available.

It’s a big honkin’ file (1.4GB), so grab a cup of coffee, lunch, or go to bed, depending on your bandwidth and the current time of day.

Extract the file using p7zip. This takes a while, so you might want to grab another coffee:

7z e Python\ for\ Android\ -\ Ubuntu\ 12.04.7z

Make sure VirtualBox is installed and the kernel module is loaded. The commands on Arch Linux are:

pacman -S virtualbox virtualbox-host-modules
sudo modprobe vboxdrv

Fire up VirtualBox and hit Machine->Add.

Navigate to the folder the vbox image was extractedto. Select the Python for Android - Ubuntu 12.04.vbox machine and hit open.

If you have enough RAM, select the Python for Android machine and hit settings. Browse to the System tab and increase the RAM to a comfortable level (I set it to 2GB on my 4GB machine). You might also want to increase the number of processors and the video RAM. Hit Start to power on the machine.

Once Ubuntu has loaded, review the README for some important information. You may want to update the VirtualBox Guest Additions install, although I’m sure it will work fine without it.

Now you’re ready to build an APK from a Python project. Open a terminal from the menu on the sidebar. The first thing you’ll want to do is update the python-for-android project to the latest git checkout. This is a bit messy because there are a couple edits in the current checkout that were later fixed upstream. So you’ll want to stash the changes before pulling:

cd android/python-for-android
git stash
git pull
git stash apply

Unfortunately, this introduces a merge conflict in The upstream project has made some of the customizations obsolete by including more generic code. Luckily, it’s a trivial fix. Open in an editor (gedit works, but I used vim.) and search for the characters =======. It’s at line 170. Delete the line above that says <<<<<<< Updated upstream. Leave the export line that was above the =======. Then delete the ======= and >>>>>>> Stashed changes and the outdated export line in between. Save the file and close the editor.

Now you need a Kivy application to install. Presumably you’ve written your own, but for this example, I’m going to use a cool one supplied by the Kivy team. The Kivy Remote Shell creates an ssh server on the phone that allows you to log in from your computer over ssh and execute Python commands on the phone. You can even run Java commands using the beta pyjnius connector.

These commands will prepare a python for android distribution ready for installation:

cd ..
git clone git://
cd python-for-android
./ -m 'openssl pycrypto pyasn1 pyjnius twisted kivy'

This will prompt to see if you want to overwrite the previous python for android distribution. Press <enter> to do so. Give it some time to connect to the network, download the dependencies from Pypi, and compile them.

Now you need a rather ugly command to actually build the apk. The options are summarized in the Python for Android documentation.

cd dist/default
./ --package org.kivy.sshshell --name "Kivy Remote Shell" \
  --version 1 --dir ../../../kivy-remote-shell/ \
  --icon ../../../kivy-remote-shell/icon.png --permission INTERNET debug

This will create the file bin/KivyRemoteShell-1-.debug.apk. Now let’s install it to the phone! First make sure USB debugging is enabled on your phone. Go to the Settings-->Developer Options menu and make sure Developer Options are enabled and that Android Debugging is enabled.

Plug the phone into your computer via the USB cord. Click the little “USB” icon in the VirtualBox status bar and check the box next to the name for your phone.

Run the command ~/android/android-sdk-linux_x86/platform-tools/adb devices to make sure it outputs the identifier of your phone. If it works, simply run ~/android/android-sdk-linux_x86/platform-tools/adb install bin/KivyRemoteShell-1-debug.apk to install the app.

(If you can’t get the phone to connect to the VM, you can also copy the .apk to the host machine to install it. Use VirtualBox’s shared folders feature).

You can now shut down the virtual machine from Ubuntu’s shutdown menu. For security, it’s a good idea to turn off USB debugging on your phone until you need it again. Run the “Kivy Remote Shell” app that is now in your phone’s app drawer. Type the command that comes up onto your screen into a terminal on your computer, and you will have access to a Python prompt running on your phone!

This same process can be used to install self-developed Kivy apps to your phone. Congratulations!

Gitifyhg: Accessing Mercurial repos from GIT

My company uses Mercurial for internal hosting. Other than that, it’s an absolutely terrific place to work.

About three quarters of my colleagues are sick of hearing the rest of us complain about Mercurial’s inadequacies. They mention tutorials like this one that simply don’t work in real life. I’ve done my research, and I have not been able to find a viable git to hg pipeline anywhere. There is a git-hg repo, but it appears to be un-maintained and not overly well documented. It’s also written in bash, so I’m not eager to take over maintenance.

Instead, I’ve been spending some of my non-working hours trying to make a python wrapper around hg-git named gitifyhg. It started out as an automated version of the hg-git tutorials, but is now expanding to provide additional support and tools.

Right now I’m following a git-svn style of workflow, where your git master branch can be synced up with the hg default branch. It seems to be working somewhat ok. I think at this point, the pain of using gitifyhg is about equal to the pain of using hg alone. Hopefully future improvements will reduce that pain, and as always, patches are most welcome!

The instructions are pretty clear and the unit tests provide a pretty good description of basic usage. Non-basic usage probably doesn’t work (yet). Here’s a tutorial of what does work:

Acme corporation uses Mercurial for all their repositories. Fred and Wilma are developing a project named AcmeAdmin together. Fred is content to use Mercurial for hosting, but Wilma is a git advocate who is going crazy with the restrictions Mercurial places on her. She decides she’s going to try gitifyhg on this new project to see how much trouble it is.

Fred starts the project by creating a Mercurial repo that will serve as the remote repo for both of them:

mkdir acmeadmin
cd acmeadmin
hg init

Fred and Wilma are doing a very strange sort of pair programming where they have separate repositories on the same machine. They are doing this so if you were reading along, you could type in the same commands they are typing and the demo would work. Rest assured that in spite of this queer practice, Fred and Wilma are hotshot programmers. So Fred now clones this remote repo and starts working. In the meantime, Wilma is browsing the gitifyhg README, so she hasn’t cloned anything yet.

cd ..
hg clone acmeadmin fredacme
cd fredacme
echo "Write Documentation" >> TODO
hg add TODO
hg commit -m "write the documentation for this project."
echo "Write Unit Tests" >>TODO
hg commit -m "unit tests are done"
hg push

Wilma’s caught up now and eager to try gitifyhg. She takes over the keyboard and clones the remote repository, which already contains Fred’s changes. Then she runs gitifyhg and verifies that a git repository exists with Fred’s two commits.

cd ..
hg clone acmeadmin wilmaacme
cd wilmaacme
git log

Fred’s gone for coffee. Wilma now starts her own hacking and pushes the commits using gitifyhg.

echo "Implement code until tests pass" >>TODO
git commit -m "code implemented" -a
git hgpush

Wilma got kind of lucky here because she implemented her code on the master branch and there were no conflicts with Fred’s work. If there had been, I’m not sure what would have happened. Fred’s finished his coffee and pulls in Wilma’s change via Mercurial. He then commits some more changes.

cd ../fredacme
hg pull -u
echo "deploy" >> TODO 
hg commit -m "it's up and running"
hg push

Meanwhile, Wilma is working on a separate feature. She remembers to create a new git branch this time, which is good because she’s going to want to do some rebasing when Fred’s commit comes in.

cd ../wilmaacme
git checkout -b feature_branch
echo "new feature documentation" >> FEATURE
git add FEATURE
git commit -m "start new feature by documenting it"

Before pushing her changes, Wilma pulls to see if Fred has done anything. He has! But the hgpull merges all that into her master branch. She checks out her working branch and rebases it onto master. Then she pushes it upstream.

git hgpull
git checkout feature_branch
git rebase master
git checkout master
git merge feature_branch
git hgpush

And that’s the basic workflow! I’m probably going to add an hgrebase command to take care of that checkout rebase checkout merge step, since I expect it to be common. It should probably use git rebase -i, which is probably the most amazing thing that ever happened to version control.

Like I said, this is how gitifyhg works when all goes well. When things don’t go well it’s still a bit of a mess. I’ve had to manually sync up the hg and git working directories using git reset --hard and hg update -C a couple times. Once, my hgpush ended up putting a bookmarked branch on my hg repo that I didn’t want to go public (luckily, hg push fails by default when there are multiple heads); I ended up having to use hg strip to clean it up. I’m hoping to automate or prevent some of this in the future. For now, try it out and submit patches or at least issues!