python - 在 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?
解决方案
问题是 kivyPrincipal
在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
of_boton
设置为该属性。然后在kv
文件中,引用该新属性:
<Principal>:
button_text:'hola2' #This line no longer throws me error.
推荐阅读
- java - Android 手机上的“受保护的应用程序”设置
- javascript - 更改类时未应用 D3 css
- pysimplegui - 如何在 PySimpleGUI 中创建时间输入字段
- azure - 希望让 Azure B2C 自定义策略使用自定义错误页面(并传递一个值)
- c# - WPF TreeView在不同级别绑定多个不同的字典并按TKey排序
- microsoft-graph-api - Graph API - 访问本地邮箱时在某些数据中心返回 404
- java - Axon:设置分布式命令总线
- ocaml - OCaml 动态链接和 -nodynlink 编译标志
- r - 如何仅打印ggplot2(R)中数据框列中的姓氏?
- asp.net-core-razor-pages - 我在使用 RazerPages 应用程序时遇到 CS1061 错误,告诉我定义不存在,但确实存在,有人可以向我指出这个问题吗?