Kivy 文档中这个示例中的 ObjectProperty 背后的想法是什么?
What's the idea behind ObjectProperty in this example from the Kivy docs?
我真的很想了解Kivy的概念。我知道它很强大而且很有用,但对我来说在某些方面也很难理解,至少在 here 中给出的例子是这样。在 "Designing with the Kivy Language" 部分中,我找到了以下示例:
Python-文件
from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty
class Controller(FloatLayout):
''' Create a controller that receives a custom widget from the kv lang file.
Add an action to be called from the kv lang file. '''
# label_wid = ObjectProperty()
info = StringProperty()
def do_action(self):
self.label_wid.text = 'My label after button press'
self.info = 'New info text'
class ControllerApp(App):
def build(self):
return Controller(info='Hello world')
if __name__ == '__main__':
ControllerApp().run()
controller.kv
<Controller>:
label_wid: my_custom_label
BoxLayout:
orientation: 'vertical'
padding: 20
Button:
text: 'My controller info is: ' + root.info
on_press: root.do_action()
Label:
id: my_custom_label
text: 'My label before button press'
与原文有一些偏差:我对行 # label_wid = ObjectProperty() 发表了评论,试图了解其背后的想法,希望代码不会 运行。不过是运行宁!那么,对 Kivy 有更好理解的人是否会如此友好地解释为什么这行代码有用(也许至少出于教育原因),如果还不需要(在任何情况下,我不知道)?
当您为不存在的 属性 添加 kv 行时,它会自动创建,因此在这种情况下 kv 实际上与将 label_wid = ObjectProperty()
放入 python。但是,在 Python 中添加 属性 更加明确(特别是如果您将从 python 访问它)并且让您确定正确类型的 属性 将是已创建。
我真的很想了解Kivy的概念。我知道它很强大而且很有用,但对我来说在某些方面也很难理解,至少在 here 中给出的例子是这样。在 "Designing with the Kivy Language" 部分中,我找到了以下示例:
Python-文件
from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty
class Controller(FloatLayout):
''' Create a controller that receives a custom widget from the kv lang file.
Add an action to be called from the kv lang file. '''
# label_wid = ObjectProperty()
info = StringProperty()
def do_action(self):
self.label_wid.text = 'My label after button press'
self.info = 'New info text'
class ControllerApp(App):
def build(self):
return Controller(info='Hello world')
if __name__ == '__main__':
ControllerApp().run()
controller.kv
<Controller>:
label_wid: my_custom_label
BoxLayout:
orientation: 'vertical'
padding: 20
Button:
text: 'My controller info is: ' + root.info
on_press: root.do_action()
Label:
id: my_custom_label
text: 'My label before button press'
与原文有一些偏差:我对行 # label_wid = ObjectProperty() 发表了评论,试图了解其背后的想法,希望代码不会 运行。不过是运行宁!那么,对 Kivy 有更好理解的人是否会如此友好地解释为什么这行代码有用(也许至少出于教育原因),如果还不需要(在任何情况下,我不知道)?
当您为不存在的 属性 添加 kv 行时,它会自动创建,因此在这种情况下 kv 实际上与将 label_wid = ObjectProperty()
放入 python。但是,在 Python 中添加 属性 更加明确(特别是如果您将从 python 访问它)并且让您确定正确类型的 属性 将是已创建。