ボタンの配置を2列×2行のグリッドに変更し、上下左右の移動ができるように修正したコードです。MDBoxLayout を MDGridLayout に変更し、フォーカス移動ロジックを2次元対応にしました。
from types import SimpleNamespace
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.uix.image import Image
from kivymd.app import MDApp
from kivymd.uix.gridlayout import MDGridLayout
from kivymd.uix.button import MDRaisedButton
from kivymd.uix.label import MDLabel
try:
import japanize_kivy
except ImportError:
pass
class KeyboardRippleButton(MDRaisedButton):
"""
カスタムボタン:
- キーボード操作時に中央からリップルを出す
- フォーカス可能
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.focus_behavior = True # フォーカス可能にする
def trigger_keyboard(self):
# キーボード操作用に中央からリップルを開始→即フェードアウト→リリースイベント
touch = SimpleNamespace(x=self.center_x, y=self.center_y, is_mouse_scrolling=False)
# RippleBehavior のメソッド呼び出し(タッチダウン相当)
self.call_ripple_animation_methods(touch)
# すぐに終了アニメーションへ
# self.finish_ripple()
# コールバック発火
Clock.schedule_once(lambda dt: self.dispatch('on_release'), 0)
class SimpleApp(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.focus_grid = [] # 2次元配列でボタンを管理
self.current_row = 0 # 現在の行
self.current_col = 0 # 現在の列
def build(self):
self.theme_cls.primary_palette = "Blue"
main_layout = MDBoxLayout(orientation='vertical', padding=10, spacing=10)
# 上部のラベルと画像
self.label = MDLabel(text="KivyMDでリップル効果付きボタン!", halign='center', font_style='H5')
image = Image(source='image.png')
main_layout.add_widget(self.label)
main_layout.add_widget(image)
# ボタングリッド (2列×2行 + 終了ボタン)
grid_layout = MDGridLayout(cols=2, spacing=10, size_hint=(1, 0.6))
exit_layout = MDBoxLayout(size_hint=(1, 0.2))
# ボタンを作成
self.btn1 = KeyboardRippleButton(text="ボタン1")
self.btn2 = KeyboardRippleButton(text="ボタン2")
self.btn3 = KeyboardRippleButton(text="ボタン3")
self.btn4 = KeyboardRippleButton(text="ボタン4")
self.exit_btn = KeyboardRippleButton(text="終了")
# 2次元配列でボタンを管理 (2行×2列)
self.focus_grid = [
[self.btn1, self.btn2], # 1行目
[self.btn3, self.btn4], # 2行目
]
# グリッドにボタンを追加
grid_layout.add_widget(self.btn1)
grid_layout.add_widget(self.btn2)
grid_layout.add_widget(self.btn3)
grid_layout.add_widget(self.btn4)
# 終了ボタン
exit_layout.add_widget(self.exit_btn)
# 最初のボタンにフォーカスを設定
self.set_focus(0, 0)
# イベントバインド
self.btn1.bind(on_release=lambda x: self.on_button_press(1))
self.btn2.bind(on_release=lambda x: self.on_button_press(2))
self.btn3.bind(on_release=lambda x: self.on_button_press(3))
self.btn4.bind(on_release=lambda x: self.on_button_press(4))
self.exit_btn.bind(on_release=lambda x: self.stop_app())
# キーボードイベント
Window.bind(on_key_down=self.on_key_down)
# レイアウト構成
main_layout.add_widget(grid_layout)
main_layout.add_widget(exit_layout)
return main_layout
def set_focus(self, row, col):
"""指定した位置のボタンにフォーカスを設定"""
# 現在のボタンの色をリセット
if 0 <= self.current_row < len(self.focus_grid) and 0 <= self.current_col < len(self.focus_grid[0]):
self.focus_grid[self.current_row][self.current_col].md_bg_color = (0.2, 0.2, 0.2, 1)
self.focus_grid[self.current_row][self.current_col].focus = False
# 新しい位置がグリッド内か確認
if 0 <= row < len(self.focus_grid) and 0 <= col < len(self.focus_grid[0]):
self.current_row, self.current_col = row, col
self.focus_grid[row][col].md_bg_color = self.theme_cls.primary_color
self.focus_grid[row][col].focus = True
# 終了ボタンの場合
elif row == 2 and col == 0:
self.current_row, self.current_col = row, col
self.exit_btn.md_bg_color = self.theme_cls.primary_color
self.exit_btn.focus = True
def move_focus(self, direction):
"""フォーカスを移動 (direction: 'up', 'down', 'left', 'right')"""
new_row, new_col = self.current_row, self.current_col
if direction == 'up' and self.current_row > 0:
new_row -= 1
elif direction == 'down' and self.current_row < 1: # グリッド内のみ
new_row += 1
elif direction == 'left' and self.current_col > 0:
new_col -= 1
elif direction == 'right' and self.current_col < 1: # グリッド内のみ
new_col += 1
elif direction == 'down' and self.current_row == 1: # 終了ボタンへ
new_row, new_col = 2, 0
elif direction == 'up' and self.current_row == 2: # グリッドへ戻る
new_row, new_col = 1, 0
self.set_focus(new_row, new_col)
def on_button_press(self, number):
self.label.text = f"ボタン{number}が押されました!"
def on_key_down(self, window, key, scancode, codepoint, modifiers):
# 数字キーで対応するボタンをトリガー
if codepoint in ['1', '2', '3', '4']:
btn = getattr(self, f"btn{int(codepoint)}")
btn.trigger_keyboard()
return True
# 十字キーでフォーカス移動
elif key == 274: # 下矢印
self.move_focus('down')
return True
elif key == 273: # 上矢印
self.move_focus('up')
return True
elif key == 276: # 左矢印
self.move_focus('left')
return True
elif key == 275: # 右矢印
self.move_focus('right')
return True
elif key == 13: # Enterキー
if self.current_row == 2 and self.current_col == 0: # 終了ボタン
self.exit_btn.trigger_keyboard()
elif 0 <= self.current_row < 2 and 0 <= self.current_col < 2: # グリッド内
self.focus_grid[self.current_row][self.current_col].trigger_keyboard()
return True
return False
def stop_app(self):
self.stop()
if __name__ == '__main__':
SimpleApp().run()