In this Kivy lesson we are going to talk about Kivy Image & Kivy AsyncImage, 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.
We want to load our image in Kivy using two ways, the first way is that you can use Python code and the second way is that you can use Kivy Deign Language. using Python code we can use kivy.ui.image module.
This is the code make sure that you have already added an image in your 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='img2.jpg') img.pos = (50,30) #img.opacity = 0.5 return img if __name__ == "__main__": window = ImageWindow() window.run() |
Using this code you can create the object of Image, also you need to add the image name, make sure that you have already added an image in your working directory.
1 |
img = Image(source='img2.jpg') |
You can change the position of the image using this code, you can give the x and y position for the image.
1 |
img.pos = (50,30) |
If you want to give opacity for the kivy image than you can use this code.
1 |
img.opacity = 0.5 |
Run the complete code and this is the result.
Now let’s load the image using Kivy AsyncImage, for this you need to have internet connection, because we want to load an image using the url.
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() |
Run the complete code and this is the result.
Creating Image with KV Language
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() |
And 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:'img2.jpg' allow_stretch:True |
Run the complete code and this is the result.