Quick search

Widget class

The Widget class is the base class required to create a Widget. This widget class is designed with a couple of principles in mind:

Event Driven
Widget interaction is built on top of events that occur. If a property changes, the widget can respond to the change in the ‘on_<propname>’ callback. If nothing changes, nothing will be done. That’s the main goal of the Property class.
Separate the widget and its graphical representation
Widgets don’t have a draw() method. This is done on purpose: The idea is to allow you to create your own graphical representation outside the widget class. Obviously you can still use all the available properties to do that, so that your representation properly reflects the widget’s current state. Every widget has its own Canvas that you can use to draw. This separation allows Kivy to run your application in a very efficient manner.
Bounding Box / Collision
Often you want to know if a certain point is within the bounds of your widget. An example would be a button widget where you want to only trigger an action when the button itself is actually touched. For this, you can use the Widget.collide_point() method, which will return True if the point you pass it is inside the axis-aligned bounding box defined by the widget’s position and size. If a simple AABB is not sufficient, you can override the method to perform the collision checks with more complex shapes, e.g. a polygon. You can also check if a widget collides with another widget with Widget.collide_widget().

We also have some default values and behaviors that you should be aware of:

  • A Widget is not a Layout: it will not change the position or the size of its children. If you want control over positioning or sizing, use a Layout.
  • The default size of a widget is (100, 100). This is only changed if the parent is a Layout. For example, if you add a Label inside a Button, the label will not inherit the buttons size or position because the button is not a Layout: it’s just another Widget.
  • The default size_hint is (1, 1). If the parent is a Layout, then the widget size will be the parent/layout size.
  • Widget.on_touch_down(), Widget.on_touch_move(), Widget.on_touch_up() don’t do any sort of collisions. If you want to know if the touch is inside your widget, use Widget.collide_point().

Using Properties

When you read the documentation, all properties are described in the format:

<name> is a <property class> and defaults to <default value>.

e.g.

text is a StringProperty and defaults to ‘’.

If you want to be notified when the pos attribute changes, i.e. when the widget moves, you can bind your own callback function like this:

def callback_pos(instance, value):
    print('The widget', instance, 'moved to', value)

wid = Widget()
wid.bind(pos=callback_pos)

Read more about Properties.

Basic drawing

Widgets support a range of drawing instructions that you can use to customize the look of your widgets and layouts. For example, to draw a background image for your widget, you can do the following:

def redraw(self, args):
    self.bg_rect.size = self.size
    self.bg_rect.pos = self.pos

widget = Widget()
with self.canvas:
    self.bg_rect = Rectangle(source="cover.jpg", pos=self.pos, size=self.size)
widget.bind(pos=redraw, size=redraw)

To draw a background in kv:

Widget:
    canvas:
        Rectangle:
            source: "cover.jpg"
            size: self.size
            pos: self.pos

These examples only scratch the surface. Please see the kivy.graphics documentation for more information.

Widget event bubbling

When you use the Kivy property changes to catch events, you sometimes need to be aware of the order in which these events are propogated. In Kivy, events bubble up from the most recently added widget and then backwards through it’s children (from the most recently added back to the first child).

In effect, this event model does not follow either of the conventional “bubble up” or “bubble down” approaches, but propogates events according to the natural order in which the widgets have been added. If you want to reverse this order, you can raise events in the children before the parent by using the super command.

Linguistically, this can be difficult to explain and sound complicated, but it’s really quite simple. Lets look at an example. In our kv file:

<EventBubbler>:
    Label:
        text: '1'
        on_touch_down: root.printme("label 1 on_touch_down")
    Label:
        text: '2'
        on_touch_down: root.printme("label 2 on_touch_down")
    BoxLayout:
        on_touch_down: root.printme("BoxLayout on_touch_down")
        Label:
            text: '3'
            on_touch_down: root.printme("label 3 on_touch_down")
        Label:
            text: '4'
            on_touch_down: root.printme("label 4 on_touch_down")
    MyBoxLayout:
        # We use this class to demonsrate using 'super' to raise the child
        # events first
        Label:
            text: '5'
            on_touch_down: root.printme("label 5 on_touch_down")
        Label:
            text: '6'
            on_touch_down: root.printme("label 6 on_touch_down")

In your Python file:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty


class EventBubbler(BoxLayout):

    @staticmethod
    def printme(msg):
        print msg


class MyBoxLayout(BoxLayout):
    def on_touch_down(self, touch):
        print "Before super(MyBoxLayout, self).on_touch_down(touch)"
        super(MyBoxLayout, self).on_touch_down(touch)
        print "After super(MyBoxLayout, self).on_touch_down(touch)"


class BubbleApp(App):
    def build(self):
        return EventBubbler()

BubbleApp().run()

This produces the following output:

>>> Before super(MyBoxLayout, self).on_touch_down(touch)
>>> label 6 on_touch_down
>>> label 5 on_touch_down
>>> After super(MyBoxLayout, self).on_touch_down(touch)
>>> BoxLayout on_touch_up
>>> label 4 on_touch_down
>>> label 3 on_touch_down
>>> label 2 on_touch_down
>>> label 1 on_touch_down

This order is the same for the on_touch_move and on_touch_up events. Notice how using the super command raises the child events immediately when it is called. This approach gives you total control over the order in which Kivy’s events are propogated.

class kivy.uix.widget.Widget(**kwargs)[source]

Bases: kivy.uix.widget.WidgetBase

Widget class. See module documentation for more information.

Events :
on_touch_down:

Fired when a new touch event occurs

on_touch_move:

Fired when an existing touch moves

on_touch_up:

Fired when an existing touch disappears

..warning::
Adding a __del__ method to a class derived from Widget with python prior to 3.4, will disable automatic garbage collection for instances of that class. That is because Widget creates ref cycles, thereby removing it from garbage collection as described here.

Changed in version 1.0.9: Everything related to event properties has been moved to the EventDispatcher. Event properties can now be used when contructing a simple class without subclassing Widget.

Changed in version 1.5.0: The constructor now accepts on_* arguments to automatically bind callbacks to properties or events, as in the Kv language.

add_widget(widget, index=0)[source]

Add a new widget as a child of this widget.

Parameters :
widget: Widget

Widget to add to our list of children.

index: int, defaults to 0

Index to insert the widget in the list

New in version 1.0.5.

>>> from kivy.uix.button import Button
>>> from kivy.uix.slider import Slider
>>> root = Widget()
>>> root.add_widget(Button())
>>> slider = Slider()
>>> root.add_widget(slider)
canvas = None

Canvas of the widget.

The canvas is a graphics object that contains all the drawing instructions for the graphical representation of the widget.

There are no general properties for the Widget class, such as background color, to keep the design simple and lean. Some derived classes, such as Button, do add such convenience properties but generally the developer is responsible for implementing the graphics representation for a custom widget from the ground up. See the derived widget classes for patterns to follow and extend.

See Canvas for more information about the usage.

center

Center position of the widget.

center is a ReferenceListProperty of (center_x, center_y)

center_x

X center position of the widget.

center_x is an AliasProperty of (x + width / 2.),

center_y

Y center position of the widget.

center_y is an AliasProperty of (y + height / 2.)

children

List of children of this widget.

children is a ListProperty and defaults to an empty list.

Use add_widget() and remove_widget() for manipulating the children list. Don’t manipulate the children list directly unless you know what you are doing.

clear_widgets(children=None)[source]

Remove all widgets added to this widget.

Changed in version 1.8.0: children argument can be used to select the children we want to remove. It should be a list of children (or filtered list) of the current widget.

cls

Class of the widget, used for styling.

collide_point(x, y)[source]

Check if a point (x, y) is inside the widget’s axis aligned bounding box.

Parameters :
x: numeric

X position of the point (in window coordinates)

y: numeric

Y position of the point (in window coordinates)

Returns :

bool, True if the point is inside the bounding box.

>>> Widget(pos=(10, 10), size=(50, 50)).collide_point(40, 40)
True
collide_widget(wid)[source]

Check if the other widget collides with this widget. Performs an axis-aligned bounding box intersection test by default.

Parameters :
wid: Widget class

Widget to collide with.

Returns :

bool, True if the other widget collides with this widget.

>>> wid = Widget(size=(50, 50))
>>> wid2 = Widget(size=(50, 50), pos=(25, 25))
>>> wid.collide_widget(wid2)
True
>>> wid2.pos = (55, 55)
>>> wid.collide_widget(wid2)
False
disabled

Indicates whether this widget can interact with input or not.

Note

1. Child Widgets, when added to a disabled widget, will be disabled automatically, 2. Disabling/enabling a parent disables/enables all it’s children.

New in version 1.8.0.

disabled is a BooleanProperty and defaults to False.

export_to_png(filename, *args)[source]

Saves an image of the widget and its children in png format at the specified filename. Works by removing the widget canvas from its parent, rendering to an Fbo, and calling save().

Note

The image includes only this widget and its children. If you want to include widgets elsewhere in the tree, you must call export_to_png() from their common parent, or use screenshot() to capture the whole window.

Note

The image will be saved in png format, you should include the extension in your filename.

New in version 1.8.1.

get_parent_window()[source]

Return the parent window.

Returns :Instance of the parent window. Can be a WindowBase or Widget.
get_root_window()[source]

Return the root window.

Returns :Instance of the root window. Can be a WindowBase or Widget.
height

Height of the widget.

height is a NumericProperty and defaults to 100.

Warning

Keep in mind that the height property is subject to layout logic and that this has not yet happened at the time of the widget’s __init__ method.

id

Unique identifier of the widget in the tree.

id is a StringProperty and defaults to None.

Warning

If the id is already used in the tree, an exception will be raised.

ids

This is a Dictionary of id’s defined in your kv language. This will only be populated if you use id’s in your kv language code.

New in version 1.7.0.

ids is a DictProperty and defaults to a empty dict {}.

on_touch_down(touch)[source]

Receive a touch down event.

Parameters :
touch: MotionEvent class

Touch received. The touch is in parent coordinates. See relativelayout for a discussion on coordinate systems.

Returns :

bool. If True, the dispatching of the touch event will stop.

on_touch_move(touch)[source]

Receive a touch move event. The touch is in parent coordinates.

See on_touch_down() for more information.

on_touch_up(touch)[source]

Receive a touch up event. The touch is in parent coordinates.

See on_touch_down() for more information.

opacity

Opacity of the widget and all the children.

New in version 1.4.1.

The opacity attribute controls the opacity of the widget and its children. Be careful, it’s a cumulative attribute: the value is multiplied by the current global opacity and the result is applied to the current context color.

For example, if the parent has an opacity of 0.5 and a child has an opacity of 0.2, the real opacity of the child will be 0.5 * 0.2 = 0.1.

Then, the opacity is applied by the shader as:

frag_color = color * vec4(1.0, 1.0, 1.0, opacity);

opacity is a NumericProperty and defaults to 1.0.

parent

Parent of this widget.

parent is an ObjectProperty and defaults to None.

The parent of a widget is set when the widget is added to another widget and unset when the widget is removed from its parent.

pos

Position of the widget.

pos is a ReferenceListProperty of (x, y) properties.

pos_hint

Position hint. This property allows you to set the position of the widget inside its parent layout, in percent (similar to size_hint).

For example, if you want to set the top of the widget to be at 90% height of its parent layout, you can write:

widget = Widget(pos_hint={'top': 0.9})

The keys ‘x’, ‘right’ and ‘center_x’ will use the parent width. The keys ‘y’, ‘top’ and ‘center_y’ will use the parent height.

See Float Layout for further reference.

Position hint is only used by the FloatLayout and Window.

pos_hint is an ObjectProperty containing a dict.

proxy_ref[source]

Return a proxy reference to the widget, i.e. without creating a reference to the widget. See weakref.proxy for more information.

New in version 1.7.2.

remove_widget(widget)[source]

Remove a widget from the children of this widget.

Parameters :
widget: Widget

Widget to remove from our children list.

>>> from kivy.uix.button import Button
>>> root = Widget()
>>> button = Button()
>>> root.add_widget(button)
>>> root.remove_widget(button)
right

Right position of the widget.

right is an AliasProperty of (x + width),

size

Size of the widget.

size is a ReferenceListProperty of (width, height) properties.

size_hint

Size hint.

size_hint is a ReferenceListProperty of (size_hint_x, size_hint_y).

See size_hint_x for more information

size_hint_x

X size hint. Represents how much space the widget should use in the direction of the X axis relative to its parent’s width. Only the Layout and Window classes make use of the hint.

The value is in percent as a float from 0. to 1., where 1. means the full size of his parent. 0.5 represents 50%.

size_hint_x is a NumericProperty and defaults to 1.

size_hint_y

Y size hint.

size_hint_y is a NumericProperty and defaults to 1.

See size_hint_x for more information

to_local(x, y, relative=False)[source]

Transform parent coordinates to local coordinates. See relativelayout for details on the coordinate systems.

Parameters :
relative: bool, defaults to False

Change to True if you want to translate coordinates to relative widget coordinates.

to_parent(x, y, relative=False)[source]

Transform local coordinates to parent coordinates. See relativelayout for details on the coordinate systems.

Parameters :
relative: bool, defaults to False

Change to True if you want to translate relative positions from a widget to its parent coordinates.

to_widget(x, y, relative=False)[source]

Convert the given coordinate from window to local widget coordinates. See relativelayout for details on the coordinate systems.

to_window(x, y, initial=True, relative=False)[source]

Transform local coordinates to window coordinates. See relativelayout for details on the coordinate systems.

top

Top position of the widget.

top is an AliasProperty of (y + height),

walk(restrict=False, loopback=False)[source]

Iterator that walks the widget tree starting with this widget and goes forward returning widgets in the order in which layouts display them.

Parameters :
restrict:

If True, it will only iterate through the widget and its children (or children of its children etc.). Defaults to False.

loopback:

If True, when the last widget in the tree is reached, it’ll loop back to the uppermost root and start walking until we hit this widget again. Naturally, it can only loop back when restrict is False. Defaults to False.

Returns:

A generator that walks the tree, returning widgets in the forward layout order.

For example, given a tree with the following structure:

GridLayout:
    Button
    BoxLayout:
        id: box
        Widget
        Button
    Widget

walking this tree:

>>> # Call walk on box with loopback True, and restrict False
>>> [type(widget) for widget in box.walk(loopback=True)]
[<class 'BoxLayout'>, <class 'Widget'>, <class 'Button'>,
    <class 'Widget'>, <class 'GridLayout'>, <class 'Button'>]
>>> # Now with loopback False, and restrict False
>>> [type(widget) for widget in box.walk()]
[<class 'BoxLayout'>, <class 'Widget'>, <class 'Button'>,
    <class 'Widget'>]
>>> # Now with restrict True
>>> [type(widget) for widget in box.walk(restrict=True)]
[<class 'BoxLayout'>, <class 'Widget'>, <class 'Button'>]

New in version 1.8.1.

walk_reverse(loopback=False)[source]

Iterator that walks the widget tree backwards starting with the widget before this, and going backwards returning widgets in the reverse order in which layouts display them.

This walks in the opposite direction of walk(), so a list of the tree generated with walk() will be in reverse order compared to the list generated with this, provided loopback is True.

Parameters :
loopback:

If True, when the uppermost root in the tree is reached, it’ll loop back to the last widget and start walking back until after we hit widget again. Defaults to False

Returns:

A generator that walks the tree, returning widgets in the reverse layout order.

For example, given a tree with the following structure:

GridLayout:
    Button
    BoxLayout:
        id: box
        Widget
        Button
    Widget

walking this tree:

>>> # Call walk on box with loopback True
>>> [type(widget) for widget in box.walk_reverse(loopback=True)]
[<class 'Button'>, <class 'GridLayout'>, <class 'Widget'>,
    <class 'Button'>, <class 'Widget'>, <class 'BoxLayout'>]
>>> # Now with loopback False
>>> [type(widget) for widget in box.walk_reverse()]
[<class 'Button'>, <class 'GridLayout'>]
>>> forward = [w for w in box.walk(loopback=True)]
>>> backward = [w for w in box.walk_reverse(loopback=True)]
>>> forward == backward[::-1]
True

New in version 1.8.1.

width

Width of the widget.

width is a NumericProperty ans defaults to 100.

Warning

Keep in mind that the width property is subject to layout logic and that this has not yet happened at the time of the widget’s __init__ method.

x

X position of the widget.

x is a NumericProperty and defaults to 0.

y

Y position of the widget.

y is a NumericProperty and defaults to 0.

class kivy.uix.widget.WidgetException[source]

Bases: exceptions.Exception

Fired when the widget gets an exception.