如何添加到kivy标签中的数字?

How to add to number in label in kivy?

我正在尝试以这种方式更新我的标签,我有一个标签和一个函数,当我使用这个函数时,我的标签在它的文本中添加了一个数字。这样,如果我点击按钮前标签是1,点击按钮后,标签变为1+x。我不知道我该怎么做。这是纯代数。

.py

class PrimeiroScreen(Screen):
def __init__(self,**kwargs):
    self.name = 'uno'
    super(Screen,self).__init__(**kwargs)

def fc(self):
    self.ids.lb1.text += "1" #its add 1 in the label, but not sum 1 to label value

and.kv

<PrimeiroScreen>:
GridLayout:
    cols: 1     
    size_hint: (.3, .1)
    pos_hint:{'x': .045, 'y': .89}
    Label:
        text:"0"
        font_size: '30dp'
        text_size: self.width, self.height
        id: lb1
    Button:
        text: "Somar 3"
        font_size: '30dp'
        text_size: self.width - 50, self.height
        on_press: root.fc()

为了通用性,我将 Label 子类化为有一个额外的 Property 来存储值,并将文本绑定到该值。允许自动格式化:

from kivy.lang import Builder
from kivy.app import App
from kivy.properties import NumericProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label

kv_str = '''
<PrimeiroScreen>:
    GridLayout:
        cols: 1     
        size_hint: (.3, .1)
        pos_hint:{'x': .045, 'y': .89}
        MyLabel:
            text: "my value: {}".format(self.value)
            font_size: '30dp'
            text_size: self.width, self.height
            id: lb1
        Button:
            text: "Somar 3"
            font_size: '30dp'
            text_size: self.width - 50, self.height
            on_press: root.fc()
'''

class PrimeiroScreen(Screen):
    def fc(self):
        self.ids.lb1.value += 1

class MyLabel(Label):
    value = NumericProperty(0)

Builder.load_string(kv_str)

class AnApp(App):
    def build(self):
        rw = ScreenManager()
        rw.add_widget(PrimeiroScreen(name='main'))
        return rw
AnApp().run()