Search code examples
pythonpython-2.7carouselkivy

Programmatically controlling a carousel in kivy


I'm new with kivy, but I have decent experience with Python and Tkinter. I'm trying to control a carousel in kivy programmatically. Essentially, I have an external python program which I want to use to automatically switch images in the carousel. To make an example, I have some code in another file:

import time

while True:
    time.sleep(1)
    #do something to control the carousel

and then I have my kivy app:

import kivy
from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.uix.image import AsyncImage

class CarouselApp(App):
    self.srcs = ["/a/bunch.png", "/of/paths.jpg", "/to/images.png."]

    def build(self):
        self.carousel = Carousel(direction="right")
        for i in range(0, len(self.srcs)):
            src = self.srcs[i]
            image = AsyncImage(source=src, allow_stretch=True)
            self.carousel.add_widget(image)
        return self.carousel

if __name__ == "__main__":
    CarouselApp().run()

I would like to be able to control which slide is displayed in the carousel using the top code, but I'm not sure how I would go about doing that, since I can't execute anything after App.run() I have investigated kivy's Clock module, but I'm not sure that would work for me since I want to switch slides when certain conditions are satisfied rather than on a time basis. The time example I gave is simply an example of my line of thinking.

Any help would be greatly appreciated!


Solution

  • I strongly suggest using a Kivy file to handle this situation. Second, AsyncImage is used when you want to use an image that will be downloaded from the Internet, and as I can see you have the images you are going to use are locally stored, so use Image instead.

    I think you should implement the method on_start in the class which is extending App (CarouselApp in this case) and schedule a function using Clock as,

    def on_start(self):
        Clock.schedule_interval(self.my_callback, 1)
    

    Then in the same class (CarouselApp) you should define my_callback:

    def my_callback(self, nap):
        if condition_is_satisfied: # this is supposed to be your condition
            # control carousel