簡述
DictProperty類專門存放字典,預設值為{}(空字典)。
基本範例
在main.py中寫上此段程式碼:
from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.properties import DictProperty class MyLayout(GridLayout) : a1 = DictProperty({'sex':'male', 'age':24}) def btn1(self): self.a1['sex'] = 'female' def on_a1(self,instance,x): print('a1 change to {}'.format(self.a1)) class Myapp(App): def build(self): return MyLayout() if __name__ == '__main__': Myapp().run()
在以上程式碼中,我在MyLayout中宣告a1為DictProperty類,其值為{'sex':'male', 'age':24},並宣告btn1方法,當btn1方法被呼叫時,指定a1字典中key為'sex'的value為'female',最後,當a1發生改變時,自動呼叫on_a1方法,列印'a1 change to {}'.format(self.a1)
在my.kv中寫上此段程式碼:
<MyLayout>: rows:2 Label: text:root.a1['sex'] Button: text: 'A1' size_hint: 0.3,0.3 on_press: root.btn1()
在以上程式碼中,我指定Label的text屬性為root.a1['sex'](root即為MyLayout)
執行結果如下:
ColorProperty使用技巧:
1.set(EventDispatcher obj, value):重新設定a1的值
在main.py中寫上此段程式碼:
from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.properties import DictProperty class MyLayout(GridLayout) : a1 = DictProperty({'sex':'male', 'age':24}) def btn1(self): self.property('a1').set(self, {'sex':'female', 'age':40}) def on_a1(self,instance,x): print('a1 change to {}'.format(self.a1)) class Myapp(App): def build(self): return MyLayout() if __name__ == '__main__': Myapp().run()
在以上程式碼中,宣告btn1方法,當btn1方法被呼叫時,指定a1字典的值為{'sex':'female', 'age':40}
在my.kv中寫上此段程式碼:
<MyLayout>: rows:2 Label: text:root.a1['sex'] Button: text: 'A1' size_hint: 0.3,0.3 on_press: root.btn1()
執行結果如下:
沒有留言:
張貼留言