Untitled conversation
- User
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.boxlayout import MDBoxLayout from kivymd.uix.button import MDRaisedButton from kivymd.uix.label import MDLabel try: import japanize_kivy except ImportError: pass class KeyboardRippleButton(MDRaisedButton): """ カスタムボタン: - キーボード操作時に中央からリップルを出す """ 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 build(self): self.theme_cls.primary_palette = "Blue" layout = MDBoxLayout(orientation='vertical', padding=10, spacing=10) self.label = MDLabel(text="KivyMDでリップル効果付きボタン!", halign='center', font_style='H5') image = Image(source='image.png') # カスタムボタンを使う self.btn1 = KeyboardRippleButton(text="ボタン1", size_hint=(1, 0.2)) self.btn2 = KeyboardRippleButton(text="ボタン2", size_hint=(1, 0.2)) self.btn3 = KeyboardRippleButton(text="ボタン3", size_hint=(1, 0.2)) exit_btn = KeyboardRippleButton(text="終了", size_hint=(1, 0.2)) # 動作をバインド for idx, btn in enumerate((self.btn1, self.btn2, self.btn3), start=1): btn.bind(on_release=lambda inst, i=idx: self.on_button_press(i)) exit_btn.bind(on_release=lambda x: self.stop_app()) # キーボード入力でリップル+イベント発火 Window.bind(on_key_down=self.on_key_down) layout.add_widget(self.label) layout.add_widget(image) layout.add_widget(self.btn1) layout.add_widget(self.btn2) layout.add_widget(self.btn3) layout.add_widget(exit_btn) return layout 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']: btn = getattr(self, f"btn{int(codepoint)}") btn.trigger_keyboard() return True def stop_app(self): self.stop() if __name__ == '__main__': SimpleApp().run()ボタンがフォーカスをとれるようにして、十字キーでフォーカスを移動するには?
Assistant
以下は、ボタンにフォーカスを付与し、十字キーでフォーカスを移動するための修正と追加コードです:
from kivy.uix.behaviors import FocusBehavior class KeyboardRippleButton(FocusBehavior, MDRaisedButton): def __init__(self, **kwargs): super().__init__(**kwargs) self.background_color_down = (0.5, 0.5, 0.5, 1) # アプリケーションクラスの修正部分 class SimpleApp(MDApp): def build(self): # フォーカス可視化のためのKVコード from kivy.lang import Builder Builder.load_string(''' <KeyboardRippleButton>: canvas.before: Color: rgba: (1,0,0,0.5) if self.focus else (0,0,0,0) Rectangle: pos: self.pos size: self.size ''') self.theme_cls.primary_palette = "Blue" layout = MDBoxLayout(orientation='vertical', padding=10, spacing=10) self.label = MDLabel(text="KivyMDでリップル効果付きボタン!", halign='center', font_style='H5') image = Image(source='image.png') self.btn1 = KeyboardRippleButton(text="ボタン1", size_hint=(1, 0.2)) self.btn2 = KeyboardRippleButton(text="ボタン2", size_hint=(1, 0.2)) self.btn3 = KeyboardRippleButton(text="ボタン3", size_hint=(1, 0.2)) self.exit_btn = KeyboardRippleButton(text="終了", size_hint=(1, 0.2)) # 初期フォーカス設定 self.btn1.focus = True # ボタンのバインディング for idx, btn in enumerate((self.btn1, self.btn2, self.btn3), start=1): btn.bind(on_release=lambda inst, i=idx: self.on_button_press(i)) self.exit_btn.bind(on_release=lambda x: self.stop_app()) # キーボード入力処理 Window.bind(on_key_down=self.on_key_down) layout.add_widget(self.label) layout.add_widget(image) layout.add_widget(self.btn1) layout.add_widget(self.btn2) layout.add_widget(self.btn3) layout.add_widget(self.exit_btn) return layout def on_key_down(self, window, key, scancode, codepoint, modifiers): buttons = [self.btn1, self.btn2, self.btn3, self.exit_btn] if codepoint in ['1', '2', '3']: btn = getattr(self, f"btn{int(codepoint)}") btn.trigger_keyboard() elif key in (273, 274, 275, 276): # 上下左右 current_focus = next((btn for btn in buttons if btn.focus), None) if current_focus: index = buttons.index(current_focus) if key == 274: # 下 next_index = (index + 1) % len(buttons) elif key == 273: # 上 next_index = (index - 1) % len(buttons) else: return True next_btn = buttons[next_index] current_focus.focus = False next_btn.focus = True elif key == 13: # Enterキー current_focus = next((btn for btn in buttons if btn.focus), None) if current_focus: current_focus.trigger_keyboard() return True変更点の説明:
-
フォーカス対応:
FocusBehaviorをボタンクラスに追加- ボタンに赤い枠でフォーカスを視覚化
-
初期設定:
btn1に初期フォーカスを設定
-
キーボード処理の追加:
- 方向キー(上下左右)でフォーカスを移動
- Enterキーでフォーカスされているボタンを押下
-
ボタン管理:
exit_btnをインスタンス変数として保持- ボタンのリスト化で管理しやすく
-
視覚フィードバック:
- フォーカス時の赤枠表示
- キーボード操作時のリップルアニメーション
使用方法:
- 数字キー1/2/3で即時操作
- 方向キーでフォーカス移動(赤枠で可視化)
- Enterキーでフォーカスされているボタンを押下
- ボタンクリックでも通常通り動作
※ フォーカス移動は垂直方向のみ対応(水平方向は無視) ※ リップルアニメーションはキーボード操作時に中央から発生します
-
- User
ボタンの配置を 1, 2 3, 4 終了 にして、上下左右の移動がテストできるようにして。
Assistant
以下のようにボタンを2×2グリッドに配置し、十字キーでフォーカス移動できるように修正します:
from kivy.uix.behaviors import FocusBehavior from kivy.uix.boxlayout import MDBoxLayout from kivy.uix.boxlayout import BoxLayout class KeyboardRippleButton(FocusBehavior, MDRaisedButton): def __init__(self, **kwargs): super().__init__(**kwargs) self.background_color_down = (0.5, 0.5, 0.5, 1) class SimpleApp(MDApp): def build(self): # フォーカス可視化のためのKVコード from kivy.lang import Builder Builder.load_string(''' <KeyboardRippleButton>: canvas.before: Color: rgba: (1,0,0,0.5) if self.focus else (0,0,0,0) Rectangle: pos: self.pos size: self.size ''') 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') # 新しいボタン4を追加 self.btn1 = KeyboardRippleButton(text="ボタン1", size_hint=(1, 0.2)) self.btn2 = KeyboardRippleButton(text="ボタン2", size_hint=(1, 0.2)) self.btn3 = KeyboardRippleButton(text="ボタン3", size_hint=(1, 0.2)) self.btn4 = KeyboardRippleButton(text="ボタン4", size_hint=(1, 0.2)) self.exit_btn = KeyboardRippleButton(text="終了", size_hint=(1, 0.2)) # 初期フォーカス設定 self.btn1.focus = True # ボタンをグリッド配置 row1 = MDBoxLayout(orientation='horizontal', spacing=10) row1.add_widget(self.btn1) row1.add_widget(self.btn2) row2 = MDBoxLayout(orientation='horizontal', spacing=10) row2.add_widget(self.btn3) row2.add_widget(self.btn4) main_layout.add_widget(self.label) main_layout.add_widget(image) main_layout.add_widget(row1) main_layout.add_widget(row2) main_layout.add_widget(self.exit_btn) # ボタンのバインディング for idx, btn in enumerate((self.btn1, self.btn2, self.btn3, self.btn4), start=1): btn.bind(on_release=lambda inst, i=idx: self.on_button_press(i)) self.exit_btn.bind(on_release=lambda x: self.stop_app()) # キーボード入力処理 Window.bind(on_key_down=self.on_key_down) return main_layout def on_key_down(self, window, key, scancode, codepoint, modifiers): buttons = [self.btn1, self.btn2, self.btn3, self.btn4, self.exit_btn] rows = [ [self.btn1, self.btn2], # 行0 [self.btn3, self.btn4], # 行1 [self.exit_btn] # 行2 ] current_focus = next((btn for btn in buttons if btn.focus), None) if current_focus is None: return True # 現在のボタンの位置を取得 current_row, current_col = None, None for r_idx, row in enumerate(rows): if current_focus in row: current_row = r_idx current_col = row.index(current_focus) break new_btn = None if key in (273, 274, 275, 276): # 上下左右 new_row, new_col = current_row, current_col if key == 273: # 上 new_row -= 1 elif key == 274: # 下 new_row += 1 elif key == 275: # 右 new_col += 1 elif key == 276: # 左 new_col -= 1 # 新しい位置が有効か確認 if 0 <= new_row < len(rows) and 0 <= new_col < len(rows[new_row]): new_btn = rows[new_row][new_col] elif key == 13: # Enterキー current_focus.trigger_keyboard() return True if new_btn is not None: current_focus.focus = False new_btn.focus = True return True return True def on_button_press(self, number): self.label.text = f"ボタン{number}が押されました!" def stop_app(self): self.stop()変更点の詳細:
-
グリッド配置:
MDBoxLayoutを縦配置のメインレイアウトに- 2x2グリッドを
MDBoxLayout(horizontal)で作成:- 行1: ボタン1と2
- 行2: ボタン3と4
- 終了ボタンを別行配置
-
フォーカス移動ロジック:
rows変数でボタンの行と列を管理- 上下左右キーで以下のように移動:
- 上下:現在の行を±1
- 左右:現在の列を±1
- 行末の場合は移動不可
- 終了ボタンへの移動は行2の列0のみ可能
-
キーボード操作:
- 数字キー1-4で直接操作可能
- 方向キーでグリッド上を移動(赤枠で可視化)
- Enterキーで選択したボタンを押下
動作例:
- 初期状態:ボタン1にフォーカス(赤枠)
- 右キー → ボタン2
- 下キー → ボタン3
- 右キー → ボタン4
- 下キー → 終了ボタン
- Enterキー → アプリ終了
この配置では、ボタンの配置が:
[ボタン1][ボタン2] [ボタン3][ボタン4] [終了]となり、十字キーでグリッド上を移動できます。
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.