Table Of Contents
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 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 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 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.
- 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 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 propogated. In Kivy, events bubble up from the most recently added widget and then backwards through its children (from the most recently added back to the first child). This order is the same for the on_touch_move and on_touch_up events.
If you want to reverse this order, you can raise events in the children before the parent by using the super command. For example:
class MyWidget(Widget):
def on_touch_down(self, touch):
super(MyWidget, self).on_touch_down(touch)
# Do stuff here
In general, this would seldom be the best approach as every event bubbles all the way through event time and there is no way of determining if it has been handled. In order to stop this event bubbling, one of these methods must return True. At this point, Kivy assumes the event has been handled and the propogation stops.
This means that the recommended approach is to let the event bubble naturally but swallow the event if it has been handled. For example:
class MyWidget(Widget):
def on_touch_down(self, touch):
If <some_condition>:
# Do stuff here and kill the event
return True
else:
# Continue normal event bubbling
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 propogated before taking action. You can use the Clock to help you here:
class MyLabel(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(MyLabel, self).on_touch_down(touch)
- 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. This is because the Widget class creates reference cycles, thereby preventing garbage collection.
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, canvas=None)[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.
- canvas: str, defaults to None
Canvas to add widget’s canvas to. Can be ‘before’, ‘after’ or None for the default canvas.
New in version 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)[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
- Child Widgets, when added to a disabled widget, will be disabled automatically.
- Disabling/enabling a parent disables/enables all of its 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.9.0.
- 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 ids defined in your kv language. This will only be populated if you use ids in your kv language code.
New in version 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)[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 its 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.
Note
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[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) properties.
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: 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.
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.9.0.
- 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: 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.
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.9.0.
- width¶
Width of the widget.
width is a NumericProperty and 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.