I created a counter inside a class to increment the value of count
count = 0
class LifeCounterApp(App):
def incr(n):
global count
count += 1
return count
I have a kv file in which I am creating the structure of my app.
What I want to do: the button "+" inside my app has to update the value of the Label.
Example: the label has default value 0
. If I click on the button the label has to change its value to 1
and so on.
My questions:
1) How to take the value of the label from the .py file?
2) The way in which I am calling the function incr
is correct? Because actually clicking on the button nothing happens.
Button:
text: "+"
on_release:
app.incr()
Label:
text: app.count (?)
Hope that my question is clear and well formulated.
You should use NumericProperty for that and not a Python global variable.
Example:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder
Builder.load_string('''
<LifeCounter>:
BoxLayout:
orientation: "vertical"
Button:
text: "+"
on_release: root.count += 1
Label:
id: l_label
text: str(root.count)
''')
class LifeCounter(BoxLayout):
count = NumericProperty(0)
def __init__(self, **kwargs):
super(LifeCounter, self).__init__(**kwargs)
class DemoApp(App):
def build(self):
return LifeCounter()
if __name__ == '__main__':
DemoApp().run()
If you want to use incr
method to increase the value of count
you can do it:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder
Builder.load_string('''
<LifeCounter>:
BoxLayout:
orientation: "vertical"
Button:
text: "+"
on_release: root.incr()
Label:
id: l_label
text: str(root.count)
''')
class LifeCounter(BoxLayout):
count = NumericProperty(0)
def __init__(self, **kwargs):
super(LifeCounter, self).__init__(**kwargs)
def incr(self):
self.count += 1
class DemoApp(App):
def build(self):
return LifeCounter()
if __name__ == '__main__':
DemoApp().run()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.