With Kivy, I understand we can use set the text
of a label to a StringProperty()
object, so whenever that string is updated, the label will automatically show the updated text.
My minimal example code, works fine, will show “apple” then “banana” one second later:
#test.kv <MyLabel>: font_size: 30 text: self.examppleStringProperty #test.py class MyLabel(Label): examppleStringProperty = StringProperty("apple") def on_kv_post(self, base_widget): Clock.schedule_interval(lambda dt : self.runlater(), 1) def runlater(self): self.examppleStringProperty = "banana" class TestApp(App): def build(self): return MyLabel()
Question: How do I do exactly the same, but for a Float? i.e have the label automatically update it’s next, whenever the value of the Float is changed?
I have a module that updates a Float value with the current room temperature, which I would just like to show on a label in Kivy, but I’m not sure how to bind it “automagically”.
I have tried NumericProperty()
, but of course I can’t set a label.text
to a NumericProperty() object, as it is not a string.
For example, the following code does not work, simply never updates the label text to the number 42, because the NumericProperty
isn’t bound to the label text in anyway.
class MyLabel(Label): examppleStringProperty = StringProperty("apple") exampleNumericProperty = NumericProperty(0) def on_kv_post(self, base_widget): self.text = str(self.exampleNumericProperty) Clock.schedule_interval(lambda dt : self.runlater(), 1) def runlater(self): self.exampleNumericProperty = 42 class TestApp(App): def build(self): return MyLabel()
Just looking for any good way to keep a Label automatically updated with the current value of a Float..
Advertisement
Answer
I have found a way to do it (Keep a label.text updated with the value of a Float), by using an “on_NumericProperty” function.
But I would appreciate any advice, if this is good or a bad design – or any suggested alternatives.
class MyLabel(Label): exampleStringProperty = StringProperty("no data yet") exampleNumericProperty = NumericProperty(0) def on_exampleNumericProperty(self, *args): self.exampleStringProperty = str(self.exampleNumericProperty) def on_kv_post(self, base_widget): Clock.schedule_interval(lambda dt : self.runlater(), 3) def runlater(self): self.exampleNumericProperty = 42 class TestApp(App): def build(self): return MyLabel()