繁体   English   中英

如何在Kivy中创建惰性属性?

[英]How can I create lazy properties in Kivy?

假设我有一个包含三个字段的类, absum 第三个应该总是等于ab的总和。

在纯Python中,这可以简单地实现为:

class MyClass(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @property
    def sum(self):
        return self.a + self.b

但是在Kivy,我们鼓励使用框架的Property描述符。 在包括sum之前,课程将是:

class MyClass(Widget):
    a = NumericProperty()
    b = NumericProperty()

    def __init__(self, a, b, **kwargs):
        super(MyClass, self).__init__(**kwargs)
        self.a = a
        self.b = b

但是,我应该如何实现sum属性? 我可以使用好的' @property 但是我不应该使用某种Kivy Property对象吗?

Kivy实现这一目标的最佳做法是什么?

通常,属性可以帮助您在窗口小部件上显示类字段的内容。 你可以使用它们。

您可以使用@property ,并创建update_sum(..)方法中的一些小部件到一个新的和重写标签,按钮上按。

或者,您可以通过创建别名属性自动执行此操作,每次更改总和时更新标签,这样您就不必单击任何按钮来更新它。

main.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty, AliasProperty


class RootBox(BoxLayout):

    a = NumericProperty()
    b = NumericProperty()

    def get_sum(self):
        return float(self.a + self.b)

    def set_sum(self, value):
        self.sum = value

    sum = AliasProperty(get_sum, set_sum, bind=['a', 'b'])

    def on_sum(self, obj, value):
        self.ids.sum_label.text = str(value)


class Test(App):
    pass


Test().run()

test.kv

RootBox:
    orientation: 'vertical'

    Label:
        id: sum_label

    BoxLayout:
        orientation: 'vertical'

        TextInput:
            on_text: root.a = float(self.text) if self.text else 0
        TextInput:
            on_text: root.b = float(self.text) if self.text else 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM