YouTubeでDerekさんによるKivy Tutorialを学ぶ②(kivy.uix.widgetまで)+日本語対応
2回目は、こちらです。
今回は、ラベルのレイアウトなので、今のうちに日本語に対応しておきましょう。
from kivy.core.text import LabelBase, DEFAULT_FONT LabelBase.register(DEFAULT_FONT, 'any-font-name.ttf')
この組み合わせで指定します。無料のフォントはあちらこちらにあります。
なお、macではこれで動きましたが、Windowsでは文字コードをShift-JISに変えて読み直しとかやってなんとか表示できました。macの方がすんなり表示できるなんて、なんか不思議。
とりあえず、基本系の
# -*- coding: utf-8 -*-
# 最初にこれを入れるみたいです。
import kivy
kivy.require("1.10.0")
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.text import LabelBase, DEFAULT_FONT
from kivy.resources import resource_add_path
# フォルダのパスを追加
resource_add_path('../fonts')
# デフォルトのフォントを変更する
LabelBase.register(DEFAULT_FONT, 'komorebi-gothic.ttf')
class CustomWidget(Widget):
pass
class CustomWidgetApp(App):
def build(self):
return CustomWidget()
if __name__ == "__main__":
CustomWidgetApp().run()
それで持ってkvファイルは以下の通りです。
# You can set default attributes that are shared by
# other widgets
# color is RGBA as a percent of 255 and alpha
# Color is the text color
# background_normal and background_down are either
# white with '' or can be set to a png
# background_color tints whatever the background is
<CustButton@Button>:
font_size: 32
color: 0, 0, 0, 1
size: 150, 50
#ボタンを押していない状態での表示用画像
background_normal: ''
#Background image of the button used for the default graphical representation when the button is pressed.
background_down: 'red.png'
background_color: .88, .88, .88, 1
# Position is x and y from the bottom left hand corner
# You can define the position based on the changing
# window sizes with root.x being the left most side
# and root.y being the bottom
<CustomWidget>:
CustButton:
text: "札幌"
pos: root.x, 200
CustButton:
text: "京都"
pos: 200, root.y
CustButton:
text: "東京"
pos: 200, 400
red.pngは、これです。

結果は、以下の通りです。ボタンを押すと背景が赤くなります。また、お分かりの通り、左下が基準(0,0)になっているようです。

この方法は、座標上の位置で指定しているので、Windowのサイズを変えると、こうなっちゃいます。

次号に続く(日本語はどこへ行った!なんてツッコミはなし)