Kivy 背景に色を付ける(Python Kivyの取説・使い方 第4回)
背景のレイアウトを追加する方法
背景に色を付けてみます。
前回のプログラムをそのまま使います。
# フル画面を解除して画面の幅と高さを設定 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)に、canvas.before:の部分を追加します。
<MainScreen>: canvas.before: Color: rgba: 0, 1, 0, 1 Rectangle: pos: self.pos size: self.size 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"
背景が緑色になりました。
画面全体に緑の背景色が付きました。ボタンの後ろも緑色です。
「color」の「rgba」の部分は、[r(赤), g(緑), b(青) ,a(透明度)]になります。有効な値の範囲は0~1です。(255までではないので注意)
「Rectangle」矩形(長方形を描写)の部分は、位置や大きさなどを指定できます。今回はBoxLayout自身の範囲いっぱいになります。
複数のレイアウトを使用する場合は全てに同じ背景を指定するのは面倒になるので、
背景を定義を別にしておくことが可能です。
# フル画面を解除して画面の幅と高さを設定 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 CustomLayout(BoxLayout): pass class TestApp(App): def build(self): self.title = 'テスト' return MainScreen() if __name__ == '__main__': TestApp().run()
kvファイル(test.kv)
<MainScreen>: CustomLayout: 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" <CustomLayout>: canvas.before: Color: rgba: 0, 1, 0, 1 Rectangle: pos: self.pos size: self.size
結果は先程と同じです。
次は真ん中のラベル部分だけ背景色を付けてみます。kvファイルだけを編集します。
<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" CustomLayout: size_hint_y: 10 Label: text: "hello World" BoxLayout: Button: text: "3" Button: text: "4" Button: text: "5" <CustomLayout>: canvas.before: Color: rgba: 0, 1, 0, 1 Rectangle: pos: self.pos size: self.size
ラベルの部分だけ緑色にできました。
出来ました!
ここであることに気付きました。
『<MainScreen>という「BoxLayout」の中に、<CustomLayout>という(背景が緑色の)「BoxLayout」を作れた』という理解で間違いないでしょうか。
それなら緑色のラベルの部分を別の新しいレイアウトを入れることもできそうです。
次回は「レイアウト イン レイアウト」をやってみまいと思います。
保存ファイル
lesson55.py
test.kv
文責:Luke