我对kivy很新。所以我在网上找到了这个代码,我不理解on_number的部分。我知道如果删除它,数字会更新,但不会重复创建窗口小部件的过程。有人可以解释一下on_number的功能是如何工作的以及这三个变量的含义是什么?
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder
Builder.load_string('''
<SubWidget1>:
Label:
text: 'number is bigger than 3'
Button:
text: 'click here to decrease'
on_press: root.parent.number -= 1
<SubWidget2>:
Label:
text: 'number is smaller than 3'
Button:
text: 'click here to increase'
on_press: root.parent.number += 1
<MyWidget>
number: 0
''')
class SubWidget1(BoxLayout):
pass
class SubWidget2(BoxLayout):
pass
class MyWidget(BoxLayout):
number = NumericProperty()
def __init__(self, *args):
super(MyWidget, self).__init__(*args)
self.widget = None
self._create_widget()
def _create_widget(self):
print(self.number)
if self.widget is not None:
self.remove_widget(self.widget)
if self.number > 3:
self.widget = SubWidget1()
else:
self.widget = SubWidget2()
self.add_widget(self.widget)
def on_number(self, obj, value):
self._create_widget()
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
答案 0 :(得分:1)
所有Kivy属性将在更改时根据属性名称自动调用其类的方法。此方法为on_propertyname
,并传递两个参数:刚刚更改其属性的对象,以及属性的新值。