Kivy:自我更新标签文字 [英] Kivy: Self-updating label text
问题描述
比方说,我有3个类:发生内容的唤醒类",标签类和包含它们的类. 例如,标签类可以是一个状态栏,显示正在上班的某物的状态.我希望我能找到一种方法来使标签自动更新要显示的值,因为该值是在后者内部更改的工作类的值.
Let's say I have 3 classes: a "woking class" where stuff takes place, a label class and a class to contain them. For example the label class could be a status bar showing the status of something going on the working class. I wish I could find a way to make the label self-update the value to show, since this value is a value of the working class being changed inside the latter.
这里有一个示例代码
Builder.load_string('''
<CustomLabel>
text: 'Value is {}'.format(root.value)
<WorkingClass>:
orientation: 'vertical'
Button:
text: 'Update'
on_release: root.update()
<MainLayout>
orientation: 'vertical'
''')
class CustomLabel(Label):
value = NumericProperty()
class WorkingClass(BoxLayout):
def __init__(self, *args, **kwargs):
super(WorkingClass, self).__init__(*args, **kwargs)
self.a = 5
def update(self):
self.a += 1
print(self.a)
class MainLayout(BoxLayout):
def __init__(self, *args, **kwargs):
super(MainLayout, self).__init__(*args, **kwargs)
self.workingClass = WorkingClass()
self.customLabel = CustomLabel(value=self.workingClass.a)
self.add_widget(self.customLabel)
self.add_widget(self.workingClass)
class MyApp(App):
def build(self):
return MainLayout()
if __name__ == "__main__":
MyApp().run()
是否可以通过属性或其他方式做到这一点?因为我不想每次更改值时都需要手动更新标签.无论如何要实现这一目标?
Is there a way of doing it with properties or whatever? Becouse I don't want to need to manually update (sommehow) the label each time I change the value. Anyway to achieve this?
推荐答案
您正在更新WorkingClass
上的属性,但这不会更新CustomLabel
上的值,因为您执行的是直接分配而不是Property
s使一切自动运行.
You're updating a property on WorkingClass
, but that doesn't update the value on CustomLabel
since you did a direct assignment instead of bind
ing it. But yes, you can use Property
s to make everything work automatically.
在WorkingClass
中:
class WorkingClass(BoxLayout):
a = NumericProperty()
def __init__(self, **kwargs): ...
这使a
成为您可以绑定到的Property
.
This makes a
into a Property
which you can bind to.
然后在MainLayout
的构造函数中:
self.workingClass = WorkingClass()
self.customLabel = CustomLabel(value=self.workingClass.a)
self.workingClass.bind(a=self.customLabel.setter('value'))
最后一行说:当self.workingClass
上的属性a
的值更改时,将self.customLabel
的value
属性设置为相同的值"
The last line says: "when the value of property a
on self.workingClass
changes, set the value
property of self.customLabel
to the same value"
或者,您可以将Property
添加到上面的WorkingClass
中,然后摆脱MainLayout
的构造函数,而使用kv代替:
Alternatively, you could just add the Property
to WorkingClass
above, then get rid of MainLayout
's constructor and use kv instead:
<MainLayout>:
orientation: 'vertical'
WorkingClass:
id: working_class
CustomLabel:
value: working_class.a # assigning one property to another in kv automatically binds
这篇关于Kivy:自我更新标签文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!