首页 > 解决方案 > 在 kv py 对象中自定义

问题描述

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

#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?

标签: pythonwidgetkivykivy-language

解决方案


问题是 kivyPrincipalkv规则中期待一个属性。由于没有这样的属性,它会引发错误。您可以通过创建执行所需操作的属性来避免该错误。如果您将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_textPrincipal类中命名的属性并将textof_boton设置为该属性。然后在kv文件中,引用该新属性:

<Principal>:
    button_text:'hola2'    #This line no longer throws me error.

推荐阅读