Search code examples
pythonkivy

Kivy to display current time on screen


Below lines are used to create a popup window to display a running string (current time) from screen right to left. (system: Windows 10)

It works as the screen pops, with no reported errors. But the screen display is blank (black).

What went wrong here?

from kivy.app import App
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.clock import Clock
from random import randint, choice
from datetime import datetime

class Danmaku(Label):
    def __init__(self, **kwargs):
        super(Danmaku, self).__init__(**kwargs)
        self.x = Window.width  # Start from the rightmost side
        self.y = Window.height // 2  # Start from the center vertically
        self.speed = 100
        self.text = datetime.now().strftime("%H:%M")
        self.color = (200, 255, 255)  # Random light colors
        self.font_size = int(0.5 * Window.height)  # Adjust font size to fill 90% of the screen height
        self.font_name = "Arial"
        self.font_hinting = None  # or remove this line, as None is the default
        self.update_text()
        self.size_hint = (None, None)  # Set size_hint to None
        self.size = self.texture_size  # Set size to the texture size

    def update_text(self):
        self.text = datetime.now().strftime("%H:%M")
        self.font_size = int(0.9 * Window.height)
        self.font_name = "Arial"
        self.color = (200, 255, 255)

    def shift(self, dt):
        self.x -= dt * self.speed

class DanmakuApp(App):
    def build(self):
        self.danmaku_list = [Danmaku()]
        self.pause_time = 1  # 1 second

        Clock.schedule_interval(self.update, 1.0 / 60.0)  # Update at 60 FPS
        return

    def update(self, dt):
        for danmaku in self.danmaku_list:
            danmaku.shift(dt)  # Update Danmaku position

        # Check if the current Danmaku has moved off the screen
        if self.danmaku_list[-1].x < -self.danmaku_list[-1].font_size:
            self.danmaku_list.append(Danmaku())  # Create a new Danmaku

    def on_resize(self, width, height):
        for danmaku in self.danmaku_list:
            danmaku.update_text()
            danmaku.size = danmaku.texture_size  # Update size to the new texture size

        return super(DanmakuApp, self).on_resize(width, height)

if __name__ == '__main__':
    DanmakuApp().run()

Solution

  • your build method for the app has to return a top-level Kivy object. Your return is empty so I changed it to this:

    return self.danmaku_list[0]
    

    that will get you closer. when I use that line, the current time scrolls slowly across the screen one time.

    there is also an on_start method you can make use of. move your clock schedule from build to on_start like this:

    def on_start(self):
        Clock.schedule_interval(self.update, 1.0 / 60.0)  # Update at 60 FPS