YouTubeでDerekさんによるKivy Tutorialを学ぶ②(kivy.uix.boxlayout)
引き続き、2回目、kivy.uix.boxlayoutについてとなります。
そのまま載せてもつまんないので、ちょっとだけ手を入れた画面はこんな感じです。

main.pyは、こんな感じです。
# main.py
# -*- coding: utf-8 -*-
import kivy
kivy.require("1.9.1")
from kivy.app import App
from kivy.core.text import LabelBase, DEFAULT_FONT
from kivy.resources import resource_add_path
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
resource_add_path('../fonts')
# ベースフォントを変更する
LabelBase.register(DEFAULT_FONT, 'komorebi-gothic.ttf')
class BoxApp(App):
def build(self):
return BoxLayout()
if __name__ == "__main__":
BoxApp().run()
特に、これっていうのはありません。続いて、box.kvはこちらです。
# box.kv
# Orientation defines whether widgets are stacked (vertical)
# or are placed side by side (horizontal)
# padding is the space between the widgets and the
# surrounding window
# orientationは、箱の並ぶ方向で垂直(vertical)か水平(horizontal)で指定します。
# paddingとspacngは、GridLayoutと同じです。
<BoxLayout>:
orientation: "vertical"
padding: 5
# size_hint defines the percentage of space taken on the
# x access and the percentage of space left over by the
# other widgets
# size_hintを使えば、特定の箱のサイズを変えられます。
Label:
font_size: 32
text: "This is BoxLayout."
size_hint: 1, None
height: 50
Button:
text: "2nd"
Button:
text: "3rd"
ここまでくると、さらに、一捻りして、入れ子(nested)構造にして見たいと思います。verticalのBoxLayoutの3段で、一番上にメニューボタンを横に並べ、2つ目をテキスト入力を入れて、3段目はラベルという感じです。

やり方をいろいろと調べたら、こんな感じです。
# main.py
# -*- coding: utf-8 -*-
import kivy
kivy.require("1.9.1")
from kivy.app import App
from kivy.core.text import LabelBase, DEFAULT_FONT
from kivy.resources import resource_add_path
from kivy.lang import Builder
resource_add_path('../fonts')
# ベースフォントを変更する
LabelBase.register(DEFAULT_FONT, 'komorebi-gothic.ttf')
class BoxApp(App):
def build(self):
# return BoxLayout()
self.root = Builder.load_file('box.kv')
return self.root
if __name__ == "__main__":
BoxApp().run()
なんか、違いますよね。Builderというのがあって、box.kvを明示的に読み込んでいる。BoxLayoutもLabelもimportしていない。box.kvはどうかっていうと。
# box.kv
BoxLayout:
orientation: 'vertical'
BoxLayout:
orientation: 'horizontal'
size_hint: None, None
height: 40
ToggleButton:
text: 'File'
ToggleButton:
text: 'Edit'
ToggleButton:
text: 'Help'
TextInput:
text: 'Default Text2'
Label:
size_hint_y: None
height: 70
text: 'This is Nested BoxLayout.'
なんで、これで動くのか理解できていない。。。kivyを続けることが辛くなってきたなぁ・・