実現したいこと
初めてKivyを使用してUIを作成しているのですが、
タイトルどおり右クリックと左クリックでGridLayout内のボタンの色をそれぞれ別の色に変更する方法がわからなかったので質問させて頂きました。
例えば、実行時はButton.background_colorはデフォルトの色([1, 1, 1, 1])で
- 左クリック時 -> Button.background_color = [1, 0, 0, 1] # Red
- 右クリック時 -> Button.background_color = [0, 0, 1, 1] # Blue
にし、もう一回同じボタンをクリックするとデフォルトの色に戻すという動作をさせたいです。
拙いコードですがよろしくお願いいたします。
問題点
以下に示しますソースコードですと、右クリックしたり、左クリックしますと、
GridLayoutにadd_module()したMyButton25個すべての色が変更されてしまいますので、これを1個だけ色を変更するように修正したいのです。
該当のソースコード
Python
1# test.py 2from kivy.app import App 3from kivy.uix.boxlayout import BoxLayout 4from kivy.uix.button import Button 5from kivy.properties import ObjectProperty 6from kivy.core.window import Window 7from kivy.config import Config 8 9Red = [1, 0, 0, 1] 10Normal = [1, 1, 1, 1] 11Blue = [0, 0, 1, 1] 12 13 14class TestApp(App): 15 16 def build(self): 17 return Gui() 18 19 20class MyButton(Button): 21 22 def __init__(self): 23 super(MyButton, self).__init__() 24 25 def on_touch_down(self, touch): 26 if touch.button == 'left': 27 if self.background_color == Red: 28 self.background_color = Normal 29 else: 30 self.background_color = Red 31 elif touch.button == 'right': 32 if self.background_color == Blue: 33 self.background_color = Normal 34 else: 35 self.background_color = Blue 36 37 38class Gui(BoxLayout): 39 grid = ObjectProperty(None) 40 41 def __init__(self, **kwargs): 42 super().__init__(**kwargs) 43 44 for i in range(5): 45 for j in range(5): 46 self.grid.add_widget(MyButton()) 47 48 49if __name__ == '__main__': 50 Config.set('input', 'mouse', 'mouse,disable_multitouch') 51 Window.size = (1500, 1000) 52 TestApp().run() 53
Kivy
1# test.kv 2<Gui>: 3 grid: Grid 4 BoxLayout: 5 size_hint_x: 0.3 6 GridLayout: 7 size_hint_x: 0.7 8 size: root.size 9 id: Grid 10 cols: 5 11 rows: 5
補足情報(FW/ツールのバージョンなど)
Python 3.6.4
Kivy 1.10.1
Cython 0.28.5
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。