Во внутренности Kivy

Каблуков Станислав

PyNSK #8
http://academmedia.com/
О себе
- Живу, учусь и работаю в Новосибирске с 2-х лет
- Вместо того что бы пойти учиться на фотомодель выбрал покупку компьютера
- Пришел в программирование через Python
- Люблю программирование, спорт зал и спать
- Свободное время посвящаю ↑
- На работе программирую на Ruby, Objective C, Swift, Java, но душа все равно тянется к Python
- Пытаюсь писать на C/C++
Как это работает?
- Код на Python
- Фреймворк Kivy
- KV разметка
- Упаковка вместе с Сython
- Генерация нативного bootstrap
Python
- Python = 2.7 Python=3
- cPython
- PyGame
Kivy Framework
- Canvas(PyGame, X11, SDL, EGL)
- Native Events (HID, VM_Touch, Mac Touch ...)
- Modules
- GPU acceleration
- RAW OpenGL support
- MultiThread
- OpenSource
- MIT license
- Properties
Properties для начало из python
class ClassWithProperty(object):
__slots__ = ('__x', 'x')
def __init__(self, x=0):
self.__x = x
def get_x_int(self):
return self.__x
def set_x_int(self, value):
self.__x = value
def del_x(self):
del self.__x
x = property(get_x_int, set_x_int, del_x, "X property")
klass_with_property = ClassWithProperty()
klass_with_property.get_x_int()
0
klass_with_property.set_x_int(10)
klass_with_property.get_x_int()
10
klass_with_property.new_attr = 19
*** AttributeError: 'ClassWithProperty' object has no attribute
'new_attr'Properties для начало из python
public class TestClass {
private int x = 0;
public int get_x() {
return x;
}
public void setX(int x) {
this.x = x;
}
}public class Main {
public static void main(String[] args){
TestClass tClass = new TestClass();
tClass.get_x();
tClass.setX(10);
tClass.y = 19; //Выдаст ошибку
}
}Properties для начало из python
class ClassWithDecorator(object):
__slots__ = ['_x']
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._xProperties для начало из python
#import <Foundation/Foundation.h>
@interface PropertyClass : NSObject
@property int x;
@property (strong, readwrite, setter=customSetterForY:, getter=customGetterForY) NSString* y;
- (NSString*)customGetterForY;
- (void)customSetterForY:(NSString*)valueOfString;
@end#import "PropertyClass.h"
@implementation PropertyClass
@synthesize y = _y;
- (NSString *)customGetterForY {
NSLog(@"y value: %@", _y);
return _y;
}
- (void)customSetterForY:(NSString *)valueOfString {
_y = valueOfString;
NSLog(@"Now y value: %@", _y);
}
@endProperties для начало из python
PropertyClass * kls = [[PropertyClass alloc] init];
kls.x;
kls.x = 12;
[kls x];
[kls setX:10];
kls.y;
kls.y = @"string custom";
[kls customGetterForY];
[kls customSetterForY:@"string custom"];@property int x;
@property (setter=customSetterForY:, getter=customGetterForY) NSString* y;
@property (strong, readonly, setter=, getter=,) obj* name;Properties
- StringProperty
- NumericProperty
- ObjectProperty
- DictProperty
- ListProperty
- BooleanProperty
- ReferenceListProperty
Properties
- Легко манипулировать виджетами, определенных в языке Kv
- Автоматически наблюдать любые изменения в коде
- Проверка и валидация значений
- Оптимизация управления памятью
Примеры
from kivy.properties import *
from kivy.uix.widget import Widget
class MyWidget(Widget):
uid = NumericProperty(0)
name = StringProperty("Widget Name")
my_list = ListProperty([])
locations = ObjectProperty()
happy = BooleanProperty(False)
number = BoundedNumericProperty(0, min=-5, max=5)
state = OptionProperty("None", options=["On", "Off", "None"])
list_property = ReferenceListProperty(uid, number)
dict_property = DictProperty({})
wid = MyWidget()
print wid.uid
0
wid.uid = "stroka" # error
my_list = wid.my_list = [1, 5, 7]
print my_list is wid.my_list
# False
my_list.append(10)
print my_list, wid.my_list
# [1, 5, 7, 10], [1, 5, 7]
print wid.happy
# FalseПримеры
Layout System
-
AnchorLayout -
BoxLayout -
FloatLayout -
RelativeLayout -
GridLayout -
PageLayout - ScatterLayout
-
StackLayout
AnchorLayout

BoxLayout

FloatLayout

Дополнительные проекты
- KivEnt - 2d игровой движок
- Kivy Designer - создания GUI дизайна мышкой для Kivy, написана на Kivy
- PyJNIus - Модуль Python для доступа к классам Java
- Pyobjus - модуль Python для доступа к классам Objective-C
KivEnt



Kivy Designer

Pyobjus
from pyobjus import autoclass
from pyobjus.dylib_manager import load_framework, INCLUDE
load_framework(INCLUDE.AppKit)
# get both nsalert and nsstring class
NSAlert = autoclass('NSAlert')
NSString = autoclass('NSString')
# shortcut to mimic the @"hello" in objective C
ns = lambda x: NSString.alloc().initWithUTF8String_(x)
# create an NSAlert object, and show it.
alert = NSAlert.alloc().init()
alert.setMessageText_(ns('Hello world!'))
alert.runModal()
Pyobjus
//Objective C
- (void) sumNumber:(int)a and:(int)b andAlso:(int)c { ... }
#Python
sumNumber_and_andAlso_(1, 2, 3)
sumNumber_A_and_B_andAlso_C(1, 2, 3)Links
- http://kivy.org
- https://github.com/kivy
- http://www.kivent.org/
- https://github.com/kivy/kivy-designer
- https://github.com/kivy/pyobjus
Вопросы?
Kivy inside
By Станислав
Kivy inside
Внутренности фрейворка kivy
- 1,132