You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy时钟应用无法自动刷新,始终显示00:00:00求助

解决Kivy时钟启动后不自动刷新的问题

你的问题核心是start类继承的BoxLayout并没有on_start这个生命周期方法,所以该方法不会被自动调用,导致时钟调度未启动。以下两种修改方案均可解决问题:

方案一:在App类中实现on_start方法

修改Python代码里的xyapp类,添加on_start方法,在这里启动时钟调度:

from kivy.config import Config
Config.set('graphics', 'width', '400')
Config.set('graphics', 'height', '600')
from kivy.app import App
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from datetime import date
from time import strftime
from kivy.clock import Clock

class start(BoxLayout):
    def update_time(self, dt):
        self.ids.time_button.text = strftime("[b]%H[/b]:%M:%S")
        
class WindowManager(ScreenManager):
    pass

kv = Builder.load_file("start.kv")

class xyapp(App):
    def build(self):
        return kv
    
    def on_start(self):
        # 获取start实例并启动时钟调度
        self.root.ids.start_widget.update_time(0)  # 立即更新一次时间,避免初始显示00:00:00
        Clock.schedule_interval(self.root.ids.start_widget.update_time, 1)

xyapp().run()

同时修改kv文件,给start组件添加id:

WindowManager:
    start:
        id: start_widget

<start>:
    BoxLayout:
        Button:
            id: time_button
            text:'[b]00[/b]:00:00'
            markup: True
            font_size: 100
            font_name: "DS-DIGIB.TTF"
            color: (.87, 0, .305, 1)
            background_color: (0.035, .094, .20, 1)

方案二:在start类中使用on_kv_post方法

on_kv_post是Widget类的内置方法,当kv文件加载完成后会自动触发,适合用来初始化调度:

修改Python代码里的start类:

class start(BoxLayout):
    def update_time(self, dt):
        self.ids.time_button.text = strftime("[b]%H[/b]:%M:%S")
    
    def on_kv_post(self, base_widget):
        # 立即更新一次时间,再启动定时调度
        self.update_time(0)
        Clock.schedule_interval(self.update_time, 1)

此方案无需修改kv文件,保持原kv代码即可。

补充说明

  • 添加self.update_time(0)是为了启动时立即显示当前时间,避免等待1秒后才刷新。
  • Clock.schedule_interval(self.update_time, 1)会每隔1秒调用一次update_time方法,实现时钟持续刷新。

内容的提问来源于stack exchange,提问作者yyxxyyxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:45:25