kivy language
kivy는 '멀티 터치' 기술이 지원됨.
'멀티 터치'를 이용하여
widget을 가지고
이동, 회전, 크기 조정 등을 할 수 있음.
(아래 영상에서 확인할 것)
kivy를 이용하여
구성 프로그램을 작성하기 위해서
우선
UI(User Interface) Component 부분을
해결해야 한다.
One of aims of the Kivy language
is to separate the concerns of presentation and logic.
The presentation (layout) side is addressed by your kv file
and
the logic by your .py file.
As your application grows more complex, it’s common that the construction of widget trees and explicit declaration of bindings becomes verbose and hard to maintain. The KV Language is an attempt to overcome these shortcomings. The KV language, sometimes called kvlang or the kivy language, allows you to create your widget tree in a declarative way and to bind widget properties to each other or to callbacks in a natural manner. It allows for very fast prototypes and agile changes to your UI. It also facilitates separating the logic of your application and its User Interface. |
[By name convention]
만약 kivy.app.App를 상속받은 클래스명이 MyApp이라면
my.kv라는 파일을 작성하게 된다.
(대소문자 구별하므로 반드시 따라야 함)
[들여쓰기]
들여쓰기도 구별하므로 반드시 따라야 한다.
Tab 보다는 Space 4개를 선호한다.
Python3에서는 Tab과 Space를 섞어 쓰지 않는다.
한줄에 최대 79 글자가 있도록 한다.
Limit all lines to a maximum of 79 characters. For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters. |
줄이 길어지면 백슬래쉬를 사용하여 여러 줄로 만든다.
with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read()) |
기타 자세한 규칙은 다음 참조
(참조: https://www.python.org/dev/peps/pep-0008/#indentation)
If this file defines a Root Widget it will be attached to the App’s root attribute and used as the base of the application widget tree. |
[Builder]
root widget을 정의한
문자열이나 파일을 load 할 때 사용.
Builder.load_file('path/to/file.kv') Builder.load_string(kv_string)
|
Rule context
Widget: |
A Kv source constitutes of rules which are used to describe the content of a Widget. You can have one root rule, and any number of class or template rules.
The root rule is declared by declaring the class of your root widget, without any indentation, followed by : and will be set as the root attribute of the App instance: |
<MyWidget>: |
A class rule, declared by the name of a widget class between < > and followed by : defines the appearance and behavior of any instance of that class: |
kvlang에서 사용할 수 있는 세 가지 키워드 |
- app: always refers to the instance of your application.
- root: refers to the base widget/template in the current rule
- self: always refer to the current widget
|
#:import name x.y.z #:import isdir os.path.isdir #:import np numpy | from x.y import z as name from os.path import isdir import numpy as np |
global value
#:set name value | name = value |
Instantiate children
MyRootWidget: BoxLayout: Button: Button: | root = MyRootWidget() box = BoxLayout() box.add_widget(Button()) box.add_widget(Button()) root.add_widget(box) |
GridLayout: cols: 3 | grid = GridLayout(cols=3) |
The value is evaluated as a Python expression, and all the properties used in the expression will be observed, that means that if you had something like this in Python (this assume self is a widget with a data ListProperty):
GridLayout: cols: len(root.data) | grid = GridLayout(cols=len(self.data)) self.bind(data=grid.setter('cols')) |
Event Bindings
Widget: on_size: my_callback() |
TextInput: on_text: app.search(args[1]) |
pos: self.center_x - self.texture_size[0] / 2., self.center_y - self.texture_size[1] / 2. |
TextInput: on_focus: print(args) |
import kivy kivy.require('1.0.6') # replace with your current kivy version !
from kivy.app import App from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput
""" [pip] > python -m virtualenv kivy_venv > kivy_venv\Scripts\activate > python -m pip install kivy [conda] conda install kivy -c conda-forge """
g_font = 'NGULIM.TTF'
class NineStarKivyGrid(GridLayout): def __init__(self, **kwargs): super(NineStarKivyGrid, self).__init__(**kwargs)
# print("kivy.kivy_home_dir: ", kivy.kivy_home_dir)
self.cols = 2
self.mybutton = Button(text='버튼: ', font_name=g_font, font_size=30) self.mybutton.bind(on_press=self.hello) self.add_widget(self.mybutton) # , font_name=my_font
self.mytextinput = TextInput(multiline=False, font_name=g_font) self.mytextinput.bind(on_text_validate=self.on_enter) self.add_widget(self.mytextinput)
self.add_widget(Label(text='라벨: ', font_name=g_font, font_size=30)) self.name = TextInput(font_name=g_font, multiline=False) self.add_widget(self.name)
def hello(self, event): print("Hello, KIVY")
def on_enter(self, event): print("you pressed Enter key.")
# sub-classing the App class class NineStarKivyAppApp(App): # icon = 'turtle.png'
# implementing its build() method so it returns a Widget instance (the root of your widget tree) def build(self): # self.icon = 'turtle.png'
# This NineStarKivyGrid will be the Root Widget of this App. return NineStarKivyGrid()
def build_config(self, config): config.setdefaults('section1', { 'key1': 'value1', 'key2': '42' })
if __name__ == '__main__': # instantiating this class, and calling its run() method. myapp = NineStarKivyAppApp() myapp.run() |
Extend canvas
MyWidget: canvas: Color: rgba: 1, .3, .8, .5 Line: points: zip(self.data.x, self.data.y) |
더 자세한 사항은 다음 참조
(참조: https://kivy.org/doc/stable/guide/lang.html)