如何覆盖 Kivy 小部件的默认值?即
MyWidget.label是“默认”但我想将其更改为例如“紫龟”是MyRootWidget的 child 吗?我可以像在
MyRootWidget.__init__()中那样访问 child 的 child ,但这看起来很麻烦,尤其是对于一棵深树...有没有更优雅的怎么做到的?
我一直在查看 Kivy lang 和 Widget 页面,但无法理解其中的解决方案。我在 SO 页面中还没有看到这个问题(尽管我在搜索时确实回答了一个不同的问题)。
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty, StringProperty
root = Builder.load_string('''
<MyWidget@BoxLayout>:
orientation: 'vertical'
Label:
id: label
text: 'DEFAULT'
<MyRootWidget@BoxLayout>:
id: root_widget
MyWidget:
id: w1
# (---1---)
''')
class MyRootWidget(BoxLayout):
w1 = ObjectProperty()
def __init__(self, **kwargs):
super().__init__(**kwargs)
print(self.ids.w1.ids.label.text) # (---2---)
class MainApp(App):
def build(self):
return MyRootWidget()
if __name__ == '__main__':
MainApp().run()
请您参考如下方法:
首先,在实现任何代码之前,您必须设计您的类。
首先,我们将使用 MyWidget 来完成它,在您的要求中,您指出您希望文本是可修改的,因此它必须是根属性。
MyWidget
┌--------------------------┐
| |
| ┌-------------┐ text---┼--->
| | Label | | |
| | *text ---┼-----┘ |
| └-------------┘ |
└--------------------------┘
MyRootWidget 也可以这样做:
MyRootWidget
┌-----------------------------┐
| |
| ┌-------------┐ obj_widget--┼--->
| | MyWidget --┼-----┘ |
| | | |
| └-------------┘ |
└-----------------------------┘
属性的深度取决于您的要求,但如果我们观察到暴露属性,则意味着在根中创建属性并进行绑定(bind),以便在修改根属性时也修改内部属性。
执行上面的代码你会得到以下结果:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty, StringProperty
root = Builder.load_string('''
<MyWidget@BoxLayout>:
text: "DEFAULT"
obj_label: label
orientation: 'vertical'
Label:
id: label
text: root.text
<MyRootWidget@BoxLayout>:
obj_widget: w1
MyWidget:
id: w1
text: "purple turtle"
''')
class MyRootWidget(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
print(self.obj_widget.text)
class MainApp(App):
def build(self):
return MyRootWidget()
if __name__ == '__main__':
MainApp().run()
因此,为了避免使用 id,您可以为子部件创建一个别名,就像我对 obj_widget 所做的那样,它是 w1 的别名。
根据设计,您不应该直接访问完整的树,但您必须修改层的属性,如果修改了该层,则必须在其内部更新必要的数据,这样我们就避免了类之间的耦合。
