In this Kivy Tutorial we want to learn about Draw Shapes in Kivy, in this lesson we want to draw different shapes like Rectangle, Circle, Triangle and Line.
So first of all you need to create a new python file, iam going to call it drawingshapes.py and you need to add this code in that file.
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.relativelayout import RelativeLayout class MyRelativeLayout(RelativeLayout): pass class DrawingWindow(App): def build(self): return MyRelativeLayout() if __name__ == "__main__": window = DrawingWindow() window.run() |
In this file we have created a class that extends from RelativeLayout, because we are going to add our shapes in the relative layout. the second class is our main class that extends from App class and we return our MyRelativeLayout class in here.
After that you need to create another file that is our .kv file, make sure that you give the name as your main window class, for example in the above code my main class name is DrawingWindow, you need to give your kivy file drawingwindow.kv. you can see that we have added our all shapes in our kivy relative layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#:kivy 1.10.0 <MyRelativeLayout>: canvas: Color: rgb:1,0,0 Rectangle: pos:200,200 size:180,180 Color: rgb:1,1,1 Ellipse: angle_start:100 angle_end:400 pos:300,300 size:130,130 Color: rgb:0,0,1 Ellipse: segments:3 pos:210,110 size:140,140 Triangle: points: 310,110,340,190,380,130 Line: points: 10,30, 90,90, 90,10, 10,60 |
Run the complete code and this is the result.
Adding Image Shapes to Kivy Window
Also you can add images in your shapes, so for this we are going to create a new python file, iam going to call it imageshapes.py. add this code in your file.
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.relativelayout import RelativeLayout class MyRelativeLayout(RelativeLayout): pass class ImageShapeWindow(App): def build(self): return MyRelativeLayout() if __name__ == "__main__": window = ImageShapeWindow() window.run() |
Now create your kivy file, my kivy file name is imageshapewindow.kv, the same as my main class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#:kivy 1.10.0 <MyRelativeLayout>: canvas: Color: rgb: 1,0,0 Ellipse: pos:200,200 size:180,180 source:'kivy.png' Color: rgb: 1,1,1 Rectangle: pos:400,200 size:180,180 source:'python.png' |
You can see that we have added a source to our shapes, make sure that you have already added some images in your working directory.
Run the complete code and this is the result