Monday, June 16, 2014

27. Widget

Widget is the root class for all other Widgets like Labels and Buttons. Since it does not have any canvas instruction of its own, you have to provide the canvas instructions for the classes derived from Widget. We will create a ball widget here.




We import the Widget class and the App class. As we will see, the Ball class draws an elliptic shape with the canvas instructions in the kv file. By clicking anywhere on the screen, the ellipse is moved there, as it's position is updated to the touch position.




The root class is based on the Widget class.


# ex27.py

from kivy.uix.widget import Widget
from kivy.app import App

class Ball(Widget):
    def on_touch_down(self, touch):
        self.center=touch.pos
    
class Ex27(Widget):
    pass
       
class Ex27App(App):
    def build(self):
        return Ex27()

if __name__=='__main__':
    Ex27App().run()



In the kv file, the Ball has a size of 65 by 60 pixels for the ellipse, and it is a reddish color. The default size of any widget would be 100 by 100 pixels, and the ellipse would be that circle size, if we did not specify a different size.




For the root class, the background color is blue.




There is a Label and the Ball widget is drawn.


# ex27.kv

<Ball>:
    size: 65,60
    canvas:
        Color:
            rgb: .75, 0, 0
        Ellipse:
            pos: self.pos
            size: self.size
    
<Ex27>:
    canvas:
        Color:
            rgb: 0,0,1
        Rectangle:
            size: root.width,root.height
            pos: 0,0
    Label:
        pos: 300,root.top-100
        text:'[size=32][color=8888CC]touch_down to move ball[/color][/size]'
        markup: True
    Ball:

        



This is the result after clicking in the middle of the screen. Most applications involve a root widget and many widget childs. We will cover some of the tutorials in the Kivy documentation such as the Pong game.




2 comments:

  1. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    Python Training in electronic city

    ReplyDelete