设置 kivy 整数的最小值和最大值

Setting minimum and maximum value for kivy integer

我有一个数字,我想从 0 到 100,不多也不少。我尝试将数字设置为:

ego = NumericProperty(0, min=0, max=100)

但是,当我按下这个按钮时,数字仍然允许自己超过 100:

on_release: root.update_ego()
Button:
    text: "increase ego"
    pos: 700,500
    on_release: root.update_ego()

我的 .py 文件是这样写的:

def update_ego(self):
    self.ego += 1

由于我不知道问题的原因(也许你必须在代码中的另一个地方设置数字),我建议这个解决方法:

def update_ego(self):
    if self.ego < 100:
        self.ego += 1

您应该执行以下操作:

from kivy.properties import BoundedNumericProperty
...
# returns the boundary value when exceeded
ego = BoundedNumericProperty(0, min=0, max=100,
    errorhandler=lambda x: 100 if x > 100 else 0)

示例 - 十进制浮点数

main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BoundedNumericProperty


class RootWidget(BoxLayout):
    ego = BoundedNumericProperty(0.0, min=0.0, max=2.0,
                                 errorhandler=lambda x: 2.0 if x > 2.0 else 0.0)

    def update_ego(self):
        print('before increment: ego={0:5.2f}'.format(self.ego))
        self.ego += 1.0
        print('after increment: ego={0:5.2f}'.format(self.ego))


class Test2App(App):

    def build(self):
        return RootWidget()


if __name__ == "__main__":
    Test2App().run()

test2.kv

#:kivy 1.10.0

<RootWidget>:
    orientation: "vertical"
    Label:
        font_size: 70
        center_x: root.width / 4
        top: root.top - 50
        text: "{0:5.2f}".format(root.ego)
    Button:
        text: "increase ego"
        on_release: root.update_ego()

输出

就像一个更新,对于那些醉酒的人来说,你完全可以更新 kivy 按钮本身的变量。

Button:
    text: "increase ego"
    on_release: root.ego = root.ego + 1

这可以减少您拥有的函数数量,并避免不必要的逻辑障碍。