Search code examples
pythonkivykivy-language

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


I'm trying to change an image every half second. I researched a little and found time.sleep doesnt working on kivy. So i need to use clock function but i didnt understand how should i use it. Can you help me ?

What i want for the program is to wait for half a second between photo changes

.py file

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 file

<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}

Solution

  • You can schedule a callback function either once or within some interval using Clock.

    One of different ways you can implement this here, is as follows,

    1. First store all images at start,

    2. Trigger a callback, say, update_image from your test method.

        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.