pythonlabelkivyclockdisplayobject

Updating multiple Labels with kivy


Hello i'm relatively new to python and kivy and I've been looking around but i cant quite find the answer, i'm trying to make a hub where I can display live data from my rasberry-pi. I made a clock widget using a Label, and it updates time, but when i try to add my CPU usage only one label shows up. I thought the widgets might be covering each other but I used size_hint and it wont help. When i run the code below, only the timex will show up and only if i delete the Clock.schedule_interval(display32.timex, (1)) will the *updatex * display.

Thanks alot for the help

from kivy.app import App

from kivy.uix.label import Label

from kivy.clock import Clock

from kivy.uix.floatlayout import FloatLayout

import psutil

from kivy.lang import Builder

import time

class Display(Label, FloatLayout):
    def __init__(self):
        super(Display, self).__init__()



    def updatex(self, *args):

        self.cpu2 = psutil.cpu_percent()
        self.text=str(self.cpu2)
        self.size_hint=(.5, .25)
        self.pos=(500, 500)
        self.texture_size=(0.1,0.1)

    def timex(self, *args):
        self.time2 = time.asctime()
        self.text = str(self.time2)
        self.size_hint = (.5, .25)
        self.pos = (30, 500)
        self.size_hint=(0.1,0.1)


class TimeApp(App):
    def build(self):
        display32 = Display()

        Clock.schedule_interval(display32.updatex, (1))
        Clock.schedule_interval(display32.timex, (1))
        return display32

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

Solution

  • Instead of passing both labels to the clock, you can define a widget, add both labels and start the clock on the widget.

    from kivy.app import App
    from kivy.uix.widget import Widget
    from kivy.uix.label import Label
    from kivy.clock import Clock
    import psutil
    import time
    
    class Display(Widget):
        def draw(self, *args):
            self.clear_widgets()
            self.add_widget(Label(text=str(psutil.cpu_percent()), pos=(500, 500)))
            self.add_widget(Label(text=str(time.asctime()), pos=(30, 500)))
    
    class TimeApp(App):
        def build(self):
            display32 = Display()
            Clock.schedule_interval(display32.draw, 1)       
            return display32
    
    if __name__ == '__main__':
        TimeApp().run()