Quick search

Widget class

The Widget class is the base class required for creating Widgets. This widget class was 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.

  • Separation Of Concerns (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 only want to trigger an action when the button itself is actually touched. For this, you can use the collide_point() method, which will return True if the point you pass to 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 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 button’s 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’s size.
  • on_touch_down(), on_touch_move(), on_touch_up() don’t do any sort of collisions. If you want to know if the touch is inside your widget, use 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 widget.canvas:
    widget.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 touch event bubbling

When you catch touch events between multiple widgets, you often need to be aware of the order in which these events are propagated. In Kivy, events bubble up from the first child upwards through the other children. If a widget has children, the event is passed through its children before being passed on to the widget after it.

As the on_touch_up() method inserts widgets at index 0 by default, this means the event goes from the most recently added widget back to the first one added. Consider the following:

box = BoxLayout()
box.add_widget(Label(text="a"))
box.add_widget(Label(text="b"))
box.add_widget(Label(text="c"))

The label with text “c” gets the event first, “b” second and “a” last. You can reverse this order by manually specifying the index:

box = BoxLayout()
box.add_widget(Label(text="a"), index=0)
box.add_widget(Label(text="b"), index=1)
box.add_widget(Label(text="c"), index=2)

Now the order would be “a”, “b” then “c”. One thing to keep in mind when using kv is that declaring a widget uses the add_widget() method for insertion. Hence, using

BoxLayout:
    MyLabel:
        text: "a"
    MyLabel:
        text: "b"
    MyLabel:
        text: "c"

would result in the event order “c”, “b” then “a” as “c” was actually the last added widget. It thus has index 0, “b” index 1 and “a” index 2. Effectively, the child order is the reverse of its listed order.

This ordering is the same for the on_touch_move() and on_touch_up() events.

In order to stop this event bubbling, a method can return True. This tells Kivy the event has been handled and the event propagation stops. For example:

class MyWidget(Widget):
    def on_touch_down(self, touch):
        If <some_condition>:
            # Do stuff here and kill the event
            return True
        else:
            return super(MyWidget, self).on_touch_down(touch)

This approach gives you good control over exactly how events are dispatched and managed. Sometimes, however, you may wish to let the event be completely propagated before taking action. You can use the Clock to help you here:

class MyWidget(Label):
    def on_touch_down(self, touch, after=False):
        if after:
            print "Fired after the event has been dispatched!"
        else:
            Clock.schedule_once(lambda dt: self.on_touch_down(touch, True))
            return super(MyWidget, self).on_touch_down(touch)

Usage of Widget.center, Widget.right, and Widget.top

A common mistake when using one of the computed properties such as Widget.right is to use it to make a widget follow its parent with a KV rule such as right: self.parent.right. Consider, for example:

FloatLayout:
    id: layout
    width: 100
    Widget:
        id: wid
        right: layout.right

The (mistaken) expectation is that this rule ensures that wid’s right will always be whatever layout’s right is - that is wid.right and layout.right will always be identical. In actual fact, this rule only says that “whenever layout’s right changes, wid’s right will be set to that value”. The difference being that as long as layout.right doesn’t change, wid.right could be anything, even a value that will make them different.

Specifically, for the KV code above, consider the following example:

>>> print(layout.right, wid.right)
(100, 100)
>>> wid.x = 200
>>> print(layout.right, wid.right)
(100, 300)

As can be seen, initially they are in sync, however, when we change wid.x they go out of sync because layout.right is not changed and the rule is not triggered.

The proper way to make the widget follow its parent’s right is to use Widget.pos_hint. If instead of right: layout.right we did pos_hint: {‘right’: 1}, then the widgets right will always be set to be at the parent’s right at each layout update.

class kivy.uix.widget.Widget(**kwargs)[ソース]

ベースクラス: 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

警告

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. This is because the Widget class creates reference cycles, thereby preventing garbage collection.

バージョン 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.

バージョン 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, canvas=None)[ソース]

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. Notice that the default of 0 means the widget is inserted at the beginning of the list and will thus be drawn on top of other sibling widgets. For a full discussion of the index and widget hierarchy, please see the Widgets Programming Guide.

バージョン 1.0.5 で追加.

canvas: str, defaults to None

Canvas to add widget’s canvas to. Can be ‘before’, ‘after’ or None for the default canvas.

バージョン 1.9.0 で追加.

>>> 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) properties.

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)[ソース]

Remove all (or the specified) children of this widget. If the ‘children’ argument is specified, it should be a list (or filtered list) of children of the current widget.

バージョン 1.8.0 で変更: The children argument can be used to specify the children you want to remove.

cls

Class of the widget, used for styling.

collide_point(x, y)[ソース]

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

Parameters:
x: numeric

x position of the point (in parent coordinates)

y: numeric

y position of the point (in parent coordinates)

Returns:

A bool. True if the point is inside the bounding box, False otherwise.

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

Check if another widget collides with this widget. This function performs an axis-aligned bounding box intersection test by default.

Parameters:
wid: Widget class

Widget to test collision with.

Returns:

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

>>> 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.

注釈

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

バージョン 1.8.0 で追加.

disabled is a BooleanProperty and defaults to False.

export_to_png(filename, *args)[ソース]

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().

注釈

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.

注釈

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

バージョン 1.9.0 で追加.

get_parent_window()[ソース]

Return the parent window.

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

Return the root window.

Returns:Instance of the root window. Can be a WindowBase or Widget.
get_window_matrix(x=0, y=0)[ソース]

Calculate the transformation matrix to convert between window and widget coordinates.

Parameters:
x: float, defaults to 0

Translates the matrix on the x axis.

y: float, defaults to 0

Translates the matrix on the y axis.

height

Height of the widget.

height is a NumericProperty and defaults to 100.

警告

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.

警告

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

ids

This is a dictionary of ids defined in your kv language. This will only be populated if you use ids in your kv language code.

バージョン 1.7.0 で追加.

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

The ids are populated for each root level widget definition. For example:

# in kv
<MyWidget@Widget>:
    id: my_widget
    Label:
        id: label_widget
        Widget:
            id: inner_widget
            Label:
                id: inner_label
    TextInput:
        id: text_input
    OtherWidget:
        id: other_widget


<OtherWidget@Widget>
    id: other_widget
    Label:
        id: other_label
        TextInput:
            id: other_textinput

Then, in python:

>>> widget = MyWidget()
>>> print(widget.ids)
{'other_widget': <weakproxy at 041CFED0 to OtherWidget at 041BEC38>,
'inner_widget': <weakproxy at 04137EA0 to Widget at 04138228>,
'inner_label': <weakproxy at 04143540 to Label at 04138260>,
'label_widget': <weakproxy at 04137B70 to Label at 040F97A0>,
'text_input': <weakproxy at 041BB5D0 to TextInput at 041BEC00>}
>>> print(widget.ids['other_widget'].ids)
{'other_textinput': <weakproxy at 041DBB40 to TextInput at 041BEF48>,
'other_label': <weakproxy at 041DB570 to Label at 041BEEA0>}
>>> print(widget.ids['label_widget'].ids)
{}
on_touch_down(touch)[ソース]

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. If False, the event will continue to be dispatched to the rest of the widget tree.

on_touch_move(touch)[ソース]

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

See on_touch_down() for more information.

on_touch_up(touch)[ソース]

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 its children.

バージョン 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. 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.

parent is an ObjectProperty and defaults to None.

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.

注釈

pos_hint is not used by all layouts. Check the documentation of the layout in question to see if it supports pos_hint.

pos_hint is an ObjectProperty containing a dict.

proxy_ref

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

バージョン 1.7.2 で追加.

remove_widget(widget)[ソース]

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) properties.

See size_hint_x for more information.

size_hint_max

Maximum size when using size_hint.

size_hint_max is a ReferenceListProperty of (size_hint_max_x, size_hint_max_y) properties.

バージョン 1.10.0 で追加.

size_hint_max_x

When not None, the x-direction maximum size (in pixels, like width) when size_hint_x is also not None.

Similar to size_hint_min_x, except that it sets the maximum width.

size_hint_max_x is a NumericProperty and defaults to None.

バージョン 1.10.0 で追加.

size_hint_max_y

When not None, the y-direction maximum size (in pixels, like height) when size_hint_y is also not None.

Similar to size_hint_min_y, except that it sets the maximum height.

size_hint_max_y is a NumericProperty and defaults to None.

バージョン 1.10.0 で追加.

size_hint_min

Minimum size when using size_hint.

size_hint_min is a ReferenceListProperty of (size_hint_min_x, size_hint_min_y) properties.

バージョン 1.10.0 で追加.

size_hint_min_x

When not None, the x-direction minimum size (in pixels, like width) when size_hint_x is also not None.

When size_hint_x is not None, it is the minimum width that the widget will be set due to the size_hint_x. I.e. when a smaller size would be set, size_hint_min_x is the value used instead for the widget width. When None, or when size_hint_x is None, size_hint_min_x doesn’t do anything.

Only the Layout and Window classes make use of the hint.

size_hint_min_x is a NumericProperty and defaults to None.

バージョン 1.10.0 で追加.

size_hint_min_y

When not None, the y-direction minimum size (in pixels, like height) when size_hint_y is also not None.

When size_hint_y is not None, it is the minimum height that the widget will be set due to the size_hint_y. I.e. when a smaller size would be set, size_hint_min_y is the value used instead for the widget height. When None, or when size_hint_y is None, size_hint_min_y doesn’t do anything.

Only the Layout and Window classes make use of the hint.

size_hint_min_y is a NumericProperty and defaults to None.

バージョン 1.10.0 で追加.

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 size_hint is used by layouts for two purposes:

  • When the layout considers widgets on their own rather than in relation to its other children, the size_hint_x is a direct proportion of the parent width, normally between 0.0 and 1.0. For instance, a widget with size_hint_x=0.5 in a vertical BoxLayout will take up half the BoxLayout’s width, or a widget in a FloatLayout with size_hint_x=0.2 will take up 20% of the FloatLayout width. If the size_hint is greater than 1, the widget will be wider than the parent.
  • When multiple widgets can share a row of a layout, such as in a horizontal BoxLayout, their widths will be their size_hint_x as a fraction of the sum of widget size_hints. For instance, if the size_hint_xs are (0.5, 1.0, 0.5), the first widget will have a width of 25% of the parent width.

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, but with widths and heights swapped.

to_local(x, y, relative=False)[ソース]

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)[ソース]

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)[ソース]

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)[ソース]

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)[ソース]

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: bool, defaults to False

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

loopback: bool, defaults to False

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.

戻り値:

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'>]

バージョン 1.9.0 で追加.

walk_reverse(loopback=False)[ソース]

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: bool, defaults to False

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.

戻り値:

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

バージョン 1.9.0 で追加.

width

Width of the widget.

width is a NumericProperty and defaults to 100.

警告

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.

exception kivy.uix.widget.WidgetException[ソース]

ベースクラス: Exception

Fired when the widget gets an exception.