繁体   English   中英

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

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

我试图每半秒更改一次图像。 我做了一些研究,发现 time.sleep 在 kivy 上不起作用。所以我需要使用时钟 function,但我不明白我应该如何使用它。 你能帮助我吗?

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

.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安排回调 function 一次或在某个时间间隔内。

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

  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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM