kivy-intro



kivy-intro

0 2


kivy-intro

Introduction to Kivy

On Github k1-hedayati / kivy-intro

Introduction to Kivy

Mr Keyvan Hedayati

Mohammad Vahshi Bafghi

Arash Shafie Hichi Abadi

This is intro, not tutorial Python & Kivy are mostly Linux based

Overview

  • What's Python?
  • What's Kivy?
  • Examples
  • Installation
  • Interface Design
  • Hello World App
  • Packaging
  • Lists and Dictionaries
  • SQlite
  • Java classes in Kivy

Testimonial

What's Python?

  • General-Purpose
  • Dynamic but Strongly Typed
  • High-Level
  • Cross Platform
  • Emphasizes on Code Readability
  • Easy to learn & code
Its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java

Not believing me? See it yourself

Compare it with Java "Hello Wolrd"

public class java {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Lines of code for XML Serialization

Python projects outperformed their C++ and Java counterparts, with less code (see right), all thanks to fast development times enabling careful tailoring and optimization. You know, the fun stuff.

Isn't that just an open-source Visual Basic?

WTF!

Who's using Python

  • Youtube, Dropbox and Instagram mainly in Python
  • Google, NASA, Yahoo!, CERN, PayPal/eBay, Bank of America
  • OpenStack Cloud Computing Software Platform (IaaS)
  • NumPy, SciPy Powerful scientific tools that compete with MATLAB
  • Embedded in 3ds Max, Blender, Cinema 4D, Lightwave, Maya, GIMP, Inkscape, ArcGIS
  • Installed by default in many Linux distributions
  • BitTorrent, Mercurial, OpenERP, ERP5, GNU Mailman
  • More Info? Read 10 Myths of Enterprise Python
Mahmoud Hashemi Lead Developer, Python Platform at eBay/PayPal PyPy‘s JIT compilation achieves faster-than-C performance Disqus scales from 250 to 500 million users on the same 100 boxes

What is Kivy?

  • Framework for making GUI applications
  • Written in Python
  • Cross platform
  • Mainly focused on mobile & touch devices
  • Ability to use Java/Objective-C classes

Why Kivy?

Fast

  • Application development
    • Agile language
  • Execution speed
    • Critical functionality implemented in C
    • Uses GPU whenever it makes sense
    • Intelligent algorithms for costly operations

Flexible

  • Run on a variety different devices and OSs
  • Quickly adapt to new technologies
    • Windows 7 Pen & Touch
    • Apple Multi-Touch
    • HID kernel input events on Linux
    • TUIO (Tangible User Interface Objects)

Funded

  • Actively developed by professionals
  • Not a small, vanishing student project

Examples

Kivy showcase app

Simple application to show some of kivy features

2048

Google Play - App Store

ProcessCraft BPMN

Google Play

Flat Jewels

Google Play

Match 3

Google Play

KOGNITIVO

Google Play

Sudoku

Google Play

QPython - Python for Android

Google Play

Installation

Windows

Download the latest version

Unzip the package

Copy the kivy.bat file to the Clipboard

Open Windows explorer, and to go the address ‘shell:sendto’

You should get the special Windows directory Send To

Paste the previously copied kivy.bat file as a shortcut

Rename it to Kivy

Execute your application by right clicking on the .py file -> “Send To” -> “Kivy ”.

Linux

(Ubuntu)
  • sudo add-apt-repository ppa:kivy-team/kivy
  • sudo apt-get install python-kivy
  • python /path/to/python/file.py

OS X

  • Download the latest version from http://kivy.org/#download
  • Double-click to open it
  • Drag the Kivy.app into your Applications folder
  • Make sure to read the Readme.txt

Interface Design

Code

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

class TestApp(App):
    def build(self):
        return Button(text='Hello World')

TestApp().run()

KV Language

# test.py
import kivy
from kivy.app import App

class TestApp(App):
    pass

TestApp().run()
# test.kv
Button:
    text: 'Hello world'

Just for the record, Java Hello Wolrd

package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloWorldActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView text = new TextView(this);
        text.setText("Hello World");
        setContentView(text);
    }
}

GUI

Via Kivy Designer (Alpha)

A Little More Than Hello World

# =========== my.kv
<HelloWorld>:
    BoxLayout:
        Label:
            id: label
            text: 'Kivy Sample App'
        Button:
            text: 'Click Me'
            on_press: root.change_text()

# =========== my.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class MyApp(App):
    def build(self):
        return HelloWorld()

class HelloWorld(BoxLayout):
    def change_text(self):
        self.ids.label.text = 'Hello Wolrd!'

MyApp().run()

Run on PC

Run on Android

Packaging

Android

(Manual)
  • Install Linux, Java, Jinja2
  • Download Android NDK, SDK
  • Download latest Android platform
  • Download python-for-android
  • Build a distribution
  • Build the APK of your application
  • Install the debug apk to your device
  • Enjoy! (your aunt spirits)

Android

(Automatic)
  • Using Buildozer pip install buildozer buildozer init
  • Edit buildozer.spec for App Name, Version, Perms, etc. buildozer android debug deploy run
  • Bouns Step - If you're on linux adb logcat | grep python

Android

(If you can't use your neighbor's uncensored Internet and/or using Windows)
  • Download Virtual Disk
  • Install VirtualBox, Import Disk Image and Run Virtual Machine
  • Build a distribution ./distribute.sh -m "kivy"
  • Build project ./build.py --dir ~/kivy/examples/demo/touchtracer \ --package org.demo.touchtracer \ --name "Kivy Touchtracer" --version 1.1.0 debug installd
  • Install it on your device adb install -r bin/KivyTouchtracer-1.1.0-debug.apk

Android

(Vahid's favorite, Cloud!)

buildozer.io

Kivy Launcher

  • Install from Google Play
  • Put your app in /sdcard/kivy/yourapplication
  • yourapplication should be a directory containing
    main.py     # Your main application file
    android.txt # Some info Kivy requires about your app on android
  • The file android.txt must contain
    title=<Application Title>
    author=<Your Name>
    orientation=<portrait|landscape>

You can package your app for Windows, Linux, MacOSX, IOS

(But I'm not going through it)

List

  • Dynamic Size
  • No Type Enforcement
  • Some methods: append, index, insert, pop, remove, reverse, sort

Examples

my_list = ['K1', 3.14, str]
my_list.append(1)
my_list.append(10)
my_list.append(15)
my_list.remove(3.14)
print len(my_list)     # 5
print my_list          # ['K1', str, 1, 10, 15]
print my_list[0]       # K1

Dictionary

  • Key-Value Data Structure
  • Uses Hash-Map For Fast Access

Examples

founded_year = {
    'Google': 2998,
    'Mi©ro$oft': 1975,
    'Apple': 1976,
    'Facebook': 2004
}
founded_year['Google'] = 1998
print founded_year['Apple'] # 1976
print founded_year          # {'Google': 1998, 'Mi©ro$oft': 1975, 'Apple': 1976, 'Facebook': 2004}
print founded_year.keys()   # ['Google', 'Mi©ro$oft', 'Apple', 'Facebook']

Other data structures

  • Set
  • OrderedDict
  • deque — Double-Ended Queue
  • heapq — Heap queue algorithm
  • bisect — Array bisection algorithm
  • array — Efficient arrays of numeric values

Simple for arrays

company_info = {
    'Google': {'founded_year': 1998, 'ceo': 'Larry Page', 'employees': 55030},
    'Mi©ro$oft': {'founded_year': 1975, 'ceo': 'Satya Nadella', 'employees': 128076},
    'Apple': {'founded_year': 1976, 'ceo': 'Tim Cook', 'employees': 98000},
    'Facebook': {'founded_year': 2004, 'ceo': 'Mark Zuckerberg', 'employees': 8348},
}

Code

This code can be cleaner

self.cols = 8
for company, info in company_info.items():
    self.add_widget(Label(text='Name: '))
    self.add_widget(Label(text=company))
    self.add_widget(Label(text='Founded Year: '))
    self.add_widget(Label(text=info['founded_year']))
    self.add_widget(Label(text='CEO: '))
    self.add_widget(Label(text=info['ceo']))
    self.add_widget(Label(text='Employees: '))
    self.add_widget(Label(text=info['employees']))

Run

SQlite

  • In-Process
  • Self-Contained
  • Serverless
  • Zero-Configuration
  • Transactional

Intro

import sqlite3

db = sqlite3.connect('db.sqlite')
db.execute('INSERT INTO members VALUES ("Gholi", "Kheshtak Zade")').commit()
members = db.execute('SELECT * FROM members').fetchall()

Simple for database

Data

CREATE TABLE companies (company_name TEXT, founded_year TEXT, ceo TEXT, employees TEXT);
INSERT INTO companies VALUES ('Google', 1998, 'Larry Page', 55030);
INSERT INTO companies VALUES ('Mi©ro$oft', 1975, 'Satya Nadella', 128076);
INSERT INTO companies VALUES ('Apple', 1976, 'Tim Cook', 98000);
INSERT INTO companies VALUES ('Facebook', 2004, 'Mark Zuckerberg', 8348);

Code

db = sqlite3.connect('db.sqlite')
company_info = db.execute('SELECT * FROM companies').fetchall()
self.cols = 8
for company in company_info:
    self.add_widget(Label(text='Name: '))
    self.add_widget(Label(text=company[0]))
    self.add_widget(Label(text='Founded Year: '))
    self.add_widget(Label(text=company[1]))
    self.add_widget(Label(text='CEO: '))
    self.add_widget(Label(text=company[2]))
    self.add_widget(Label(text='Employees: '))
    self.add_widget(Label(text=company[3]))

Run

Bonus Slide

Java classes in Kivy

You can use android classes using PyJnius

from time import sleep
from jnius import autoclass

Hardware = autoclass('org.renpy.android.Hardware')
print 'DPI is', Hardware.getDPI()

Hardware.accelerometerEnable(True)
for i in range(20):
    print Hardware.accelerometerReading()
    sleep(.1)

Thanks For Your Attention

(And Affection!)

0