This is our sixth article on Kivy Crash Course, in this article we are going to to learn about Image & AsyncImage Example. so the Image
widget is used to display an image. to load an image asynchronously (for example from an external webserver), use the AsyncImage
subclass.
Also you can watch the video for this article
Kivy Crash Course Articles
1: Kivy Crash Course Introduction & Installation
2: Introduction to Kv Design Language
5: Kivy How to Create CheckBox
So there are two ways that you can create images in kivy, the first way is that you can create image using the kivy.uix.image module, and the second way is using the kivy design language, so first let’s just do the first way.
First let’s use an image from our working directory, i have already copied a image in my working directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
from kivy.app import App from kivy.uix.image import Image class ImageWindow(App): def build(self): img = Image(source='mypic.jpg') img.pos = (300,300) img.opacity = 0.5 return img if __name__ == "__main__": window = ImageWindow() window.run() |
So you can see at the top first we have created the object of Image class, and we have passed the image name as source to the constructor of the class. also we have given position to the image with opacity. if you run the code this will be the result.
Now if you want to load an image from the internet, for this purpose you need to use AsyncImage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
from kivy.app import App from kivy.uix.image import AsyncImage class ImageWindow(App): def build(self): img = AsyncImage(source = "https://kivy.org/logos/kivy-logo-black-64.png") return img if __name__ == "__main__": window = ImageWindow() window.run() |
If you run the code this will be the result
So now let’s create the image using the kivy file, so first of all this is my python code. in this code basically i have just created a new class that extends from the image class and i have returned that class in my main app class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from kivy.app import App from kivy.uix.image import Image class MyImage(Image): pass class ImageWindow(App): def build(self): return MyImage() if __name__ == "__main__": window = ImageWindow() window.run() |
Now this is our .kv file, and i have name the file imagewindow.kv, make sure that this name should similar to the main app class name, in my case it is ImageWindow class.
1 2 3 4 5 6 7 |
#kivy 1.10.0 <MyImage>: source:'mypic.jpg' allow_stretch:True |
If you run the code this will be the result
Subscribe and Get Free Video Courses & Articles in your Email