【问题标题】:Customize in kv py object在 kv py 对象中自定义
【发布时间】:2020-03-19 05:33:07
【问题描述】:

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

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

【问题讨论】:

标签: python widget kivy kivy-language


【解决方案1】:

问题是 kivy 在kv 规则中期望Principal 的属性。由于没有这样的属性,它会引发错误。您可以通过创建执行所需操作的属性来避免该错误。如果您将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)

这会在Principal 类中创建一个名为button_text 的属性,并将_botontext 设置为该属性。然后在kv 文件中,引用该新属性:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2015-07-10
    相关资源
    最近更新 更多