Search code examples
pythonsumkivytextlabel

How to add to number in label in kivy?


I am trying to update my label in this way, I have a label and a function, when I use this function, my label add a number in it's text. In this way, if my label is 1 before I click the button, after I click a button, the label change to 1+x. I have no idea how can I do this. It's pure algebra.

.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()

Solution

  • For sake of generalizability, I would subclass Label to have an additional Property to store the value, and bind the text to that value. That allows automatic formatting:

    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()