在KV PY对象中自定义

时间:2019-11-23 09:21:21

标签: python widget kivy kivy-language

我需要知道如何自定义已实例化的对象。

#Archivo py
class Principal(ScreenManager):
    def __init__(self, **kwargs):
        super(Principal, self).__init__(**kwargs)
        self._principal=Screen(name='Principal')
        self._layout=AnchorLayout()
        self._boton=Button(text='Hola')

        self._layout.add_widget(self._boton)
        self._principal.add_widget(self._layout)
        self.add_widget(self._principal)
#Archivo kv
#:kivy 1.11.1
<Principal>:
    root._boton.text:'hola2'    #This line throws me error. How do I change the text of the button?

1 个答案:

答案 0 :(得分:0)

问题是kivy在Principal规则中期望kv的属性。由于没有此类属性,因此会引发错误。您可以通过创建符合您要求的属性来避免该错误。如果您将Principal类更改为:

class Principal(ScreenManager):
    button_text = StringProperty('Hola') # new attribute

    def __init__(self, **kwargs):
        super(Principal, self).__init__(**kwargs)
        self._principal=Screen(name='Principal')
        self._layout=AnchorLayout()
        self._boton=Button(text=self.button_text)  # use of new attribute
        self._layout.add_widget(self._boton)
        self._principal.add_widget(self._layout)
        self.add_widget(self._principal)

这将在button_text类中创建一个名为Principal的属性,并将text的{​​{1}}设置为该属性。然后在_boton文件中,引用该新属性:

kv