我如何在 kivy 中使用时钟而不是 time.sleep?

How can i use clock instead of time.sleep in kivy?

我正在尝试每半秒更改一次图像。我进行了一些研究,发现 time.sleep 不适用于 kivy。所以我需要使用时钟功能,但我不明白我应该如何使用它。你能帮帮我吗?

我想要的程序是在照片更改之间等待半秒

.py 文件

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.screenmanager import NoTransition
from kivy.properties import StringProperty
import time


class MainPage(Screen):
    img_ico = StringProperty("./img/testico1.png")

    def test(self):
        for _ in range(0, 3):   # Changes the image 3 times
            self.ids.my_ico1.source = './img/testico2.png'
            self.ids.my_ico1.reload()
            time.sleep(0.5)     # What should i use instead of time.sleep ?
            self.ids.my_ico1.source = './img/testico1.png'
            self.ids.my_ico1.reload()
            time.sleep(0.5)     # What should i use instead of time.sleep ?


class MyApp(App):
    def build(self):
        global sm
        sm = ScreenManager(transition=NoTransition())
        sm.add_widget(MainPage(name='mainpage'))
        return sm


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

.kv 文件

<MainPage>
    FloatLayout:
        Button:
            text:"Test Button"
            size_hint: 0.35,0.075
            pos_hint: {"x": 0.1, "top": 0.9}
            on_release:
                root.test()

        Image:
            id: my_ico1
            source: root.img_ico
            size_hint_x: 0.04
            allow_stretch: True
            pos_hint: {"x": 0.2, "top": 0.7}

您可以使用 Clock.

安排一次或在某个时间间隔内安排回调函数

您可以在此处实现的不同方法之一如下,

  1. 首先存储所有图片,

  2. 从您的 test 方法触发回调,例如 update_image

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.images = ['./img/testico1.png', './img/testico2.png'] # Store all images here.
        self.index = 0 # Set a index to iterate over.

    def update_image(self, dt): # Callback function.
        i = self.index%len(self.images) # You can set your desired condition here, stop the callback etc. Currently this will loop over self.images.
        self.ids.my_ico1.source = self.images[i]
        self.index += 1

    def test(self):
        Clock.schedule_interval(self.update_image, 0.5) # It will schedule the callback after every 0.5 sec.