Kivy kvファイルを使ってレイアウトを変更する(Python Kivyの取説・使い方 第3回)
kvファイルとは?
Appで終わるクラス名からAppを引いた小文字で同じ名前を持つkvファイルを呼び出します。例えば、class TestApp(App):の場合は kvファイルの名前は「test.kv」です。
ラベルやボタンなどのレイアウト情報を別ファイルで管理して簡単に調整できます。
前回、ラベルとボタンを縦に並べたプログラムでkvファイルを作ってみます。
# フル画面を解除して画面の幅と高さを設定 from kivy.config import Config Config.set('graphics', 'fullscreen', 0) Config.set('graphics', 'width', 320) Config.set('graphics', 'height', 568) Config.set('graphics', 'resizable', 0) from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Label from kivy.uix.button import Button class MainScreen(BoxLayout): pass class TestApp(App): def build(self): self.title = 'テスト' return MainScreen() if __name__ == '__main__': TestApp().run()
kvファイル(test.kv)
<MainScreen>: orientation: "vertical" Label: text: "hello" Button: text: "World"
kvファイルの編集
それでは、kvファイルだけを触ってレイアウトを変更してみます。
<MainScreen>: BoxLayout: orientation: "vertical" BoxLayout: Button: text: "1" Button: text: "2" Label: text: "hello World" BoxLayout: Button: text: "3" Button: text: "4" Button: text: "5"
このように「BoxLayout」の中に「BoxLayout」を作ることも可能です。
もう少しでスマホアプリっぽい画面になりそうです。
サイズの変更
<MainScreen>: BoxLayout: orientation: "vertical" BoxLayout: Button: size_hint_x: 0.2 text: "1" Label: size_hint_x: 0.6 text: "today" Button: size_hint_x: 0.2 text: "2" Label: size_hint_y: 10 text: "hello World" BoxLayout: Button: text: "3" Button: text: "4" Button: text: "5"
size_hintを使って大きさを変更できます。0.2 0.6 0.2 のように全体の比率にしてもいいですし、size_hint_y: 10 のように10行分の高さと指定することもできます。
こんな感じになりました。
スマホアプリっぽいレイアウトになってきました。
本日は以上です。
保存ファイル
lesson54.py
test.kv
文責:Luke