Today I will talk about two interesting Widgets of the Kivy framework. Both these widgets can be used to display/load images in a particular manner.
As mentioned in the Kivy docs, the Carousel widget provides a mobile-friendly carousel view where one can swipe between slides. One can add any content to the carousel and use it horizontally or vertically. The carousel can display pages in loop. One can also navigate to the next slide or the previous slide using the Carousel properties.
Here's how we can use the Carousel view!
Step 1: Create a folder named images on your disk and copy a few pictures inside that folder. I have added a few images for my project. Download the source code from the below link to view them.
Step 2: Open the Python IDLE. Create a new Python script and type the following code!
from kivy.app import App from kivy.uix.carousel import Carousel from kivy.factory import Factory from kivy.uix.image import Image class Example1(App): def build(self): #define the carousel carousel = Carousel(direction='right',loop='true') for i in range(1,5): #load pictures from images folder src = "images/%d.jpg" % i image = Image(source=src,pos=(400, 100), size=(400, 400)) carousel.add_widget(image) return carousel if __name__ == '__main__': Example1().run()
Step 3: Save the file as Example1.py. Make sure to save the Python file inside the same directory as that of the images folder.
Step 4: Open command prompt. Navigate to the directory where you have your Python script. Type kivy Example1.py and press enter. You should get a carousel view of various fruit images!
Now, the AsyncImage class is used to load images asynchronously from an external webserver. All one needs to do is specify the URL of the website that contains the data. One can use AsyncImage in combination with Carousel to load and display images.
Once again create a new Python script. Add the following code. Run it as explained previously and you should see some images getting loaded asynchronously!
Here's a short implementation of the AsyncImage class along with the Carousel view.
from kivy.app import App from kivy.uix.carousel import Carousel from kivy.factory import Factory from kivy.uix.image import Image class Example1(App): def build(self): carousel = Carousel(direction='right',loop='true') for i in range(1,5): src = "http://placehold.it/480x270.png&text=slide-%d&.png" % i #load images asynchronously image = Factory.AsyncImage(source=src, allow_stretch=True) carousel.add_widget(image) return carousel if __name__ == '__main__': Example1().run()
So that's it for this post. I will talk about the Graphics module of the Kivy framework in my further posts! Enjoy! 😄