如何在 Kivy 中有更新时间

2022-01-15 00:00:00 python kivy

问题描述

我正在 kivy 中创建日历应用程序,我想知道如何添加更新时钟?我可以使用 datetime python 函数,但是当我在我的应用程序中加载它时,它会显示一个没有移动的冻结时间.有什么建议吗?

I am creating a calendar app in kivy, and I was wondering how I would be able to add an updating clock? I can use the datetime python function, but when I load it in my app it shows a frozen time with no movement. Suggestions?

from datetime import datetime, date, time, timedelta
from kivy.app import App
from kivy.clock import Clock

(已解决)


解决方案

这里有一个完整的例子来说明如何使用这个功能.您应该能够从中工作并将其应用于您自己的代码.如果您有任何具体问题,请在评论中告诉我,我很乐意回答:)

Here's a complete example of how to get this feature working. You should be able to work from this and apply it to your own code. If you have any specific questions, let me know in a comment and I'll be happy to answer :)

from kivy.app import App
from datetime import datetime
from datetime import timedelta
from kivy.clock import Clock
from kivy.uix.label import Label

class MyApp(App):
    def build(self):
        self.now = datetime.now()

        # Schedule the self.update_clock function to be called once a second
        Clock.schedule_interval(self.update_clock, 1)
        self.my_label = Label(text= self.now.strftime('%H:%M:%S'))
        return self.my_label  # The label is the only widget in the interface

    def update_clock(self, *args):
        # Called once a second using the kivy.clock module
        # Add one second to the current time and display it on the label
        self.now = self.now + timedelta(seconds = 1)
        self.my_label.text = self.now.strftime('%H:%M:%S')

MyApp().run()

相关文章