Widget

Provides the base Widget and PyWidget classes.

When subclassing a Widget to create a compound widget (i.e. a widget that contains other widgets), initialize the child widgets inside the init() method. That method is called while the widget is the current widget; any widgets instantiated inside it will automatically become children.

from flexx import flx

class Example(flx.Widget):
    def init(self):
        super().init()

        flx.Button(text='foo')
        flx.Button(text='bar')
open in new tab

One can also use a widget as a context manager (i.e. using the with statement) to create child widgets. This is particularly useful for layout widgets (like HBox).

from flexx import flx

class Example(flx.Widget):
    def init(self):
        super().init()

        with flx.HBox():
            flx.Button(flex=1, text='foo')
            flx.Button(flex=2, text='bar')
open in new tab

In the above two examples, the newly created classes subclass from Widget and are thus a JsComponent (i.e. operate in JS). This may be what you want if you are aiming for a UI that can be exported for the web. If, however, you are developing a desktop application, consider subclassing from PyWidget instead, which will make your widget operate in Python.

It is also possible to create custom low-level widgets by implementing _render_dom(), resulting in a declarative “react-like” (but less Pythonic) approach. It returns a virtual DOM that is used to update/replace the real browser DOM.

from flexx import flx

class Example(flx.Widget):

    count = flx.IntProp()

    def _render_dom(self):
        # This method automatically gets called when any of the used
        # properties (only count, in this case) changes.
        return flx.create_element('div', {},
            flx.create_element('button',
                               {'onclick': self.increase_count},
                               '+'),
            flx.create_element('span',
                               {'style.background': '#afa'},
                               str(self.count)),
            )

    @flx.action
    def increase_count(self):
        self._mutate_count(self.count + 1)
open in new tab


flexx.ui.create_element(type, props=None, *children)

Convenience function to create a dictionary to represent a virtual DOM node. Intended for use inside Widget._render_dom().

The content of the widget may be given as a series/list of child nodes (virtual or real), and strings. Strings are converted to text nodes. To insert raw HTML, use the innerHTML prop, but be careful not to include user-defined text, as this may introduce openings for XSS attacks.

The returned dictionary has three fields: type, props, children.

class flexx.ui.PyWidget(*args, **kwargs)

Inherits from: PyComponent

A base class that can be used to create compound widgets that operate in Python. This enables an approach for building GUI’s in a Pythonic way: by only using JS components (actual widgets) all code that you write can be Python code.

Internally, objects of this class create a sub-widget (a flx.Widget instance). When the object is used as a context manager, the sub-widget will also become active. Further, this class gets attributes for all the sub-widget’s properties, actions, and emitters. In effect, this class can be used like a normal flx.Widget (but in Python).

JS

alias of PyWidget

class flexx.ui.Widget(*init_args, **kwargs)

Inherits from: JsComponent

Base widget class (a Component in JS wrapping an HTML element).

When subclassing a Widget, it is recommended to not implement the __init__() method, but instead implement init() for compound (higher-level) widgets, and _create_dom() for low-level widgets.

Widgets can be styled using CSS by implementing a string class attribute named CSS. A widget’s node has a CSS-class-name corresponding to its Python class (and its base classes), following the scheme flx-WidgetClassName.

All widgets have a node and outernode attribute (only accessible in JavaScript), representing the DOM element(s) that represent the widget. For most types of widgets, node is equal to outernode. For the Widget class, this is simply a <div> element. If you don’t understand what this is about, don’t worry; you won’t need it unless you are creating your own low-level widgets. See _create_dom() for details.

When implementing your own widget class, the class attribute DEFAULT_MIN_SIZE can be set to specify a sensible minimum size.

properties: capture_mouse, children, container, css_class, flex, icon, maxsize, minsize, minsize_from_children, parent, size, tabindex, title

emitters: key_down, key_press, key_up, pointer_cancel, pointer_click, pointer_double_click, pointer_down, pointer_move, pointer_up, pointer_wheel

actions: apply_style, check_real_size, set_capture_mouse, set_container, set_css_class, set_flex, set_icon, set_maxsize, set_minsize, set_minsize_from_children, set_parent, set_tabindex, set_title

methods: _create_dom, _render_dom, dispose, init

_create_dom()

Create DOM node(s) for this widget.

This method must return two (real or virtual) DOM nodes which will be available as self.outernode and self.node respectively. If a single node is given, it is used for both values. These attributes must remain unchanged throughout the lifetime of a widget. This method can be overloaded in subclasses.

Most widgets have the same value for node and outernode. However, in some cases it helps to distinguish between the semantic “actual node” and a wrapper. E.g. Flexx uses it to properly layout the CanvasWidget and TreeItem. Internally, Flexx uses the node attribute for tab-index, and binding to mouse/touch/scroll/key events. If your outernode already semantically represents your widget, you should probably just use that.

_render_dom()

Update the content of the DOM for this widget.

This method must return a DOM structure consisting of (a mix of) virtual nodes, real nodes and strings. The widget will use this structure to update the real DOM in a relatively efficient manner (new nodes are only (re)created if needed). The root element must match the type of this widget’s outernode. This method may also return a list to apply as the root node’s children.

Note that this method is called from an implicit reaction: it will auto-connect to any properties that are accessed. Combined with the above, this allows for a very declarative way to write widgets.

Virtual nodes are represented as dicts with fields “type”, “props” and “children”. Children is a list consisting of real dom nodes, virtual nodes, and strings. Strings are converted to TextNode (XSS safe). The create_element() function makes it easy to create virtual nodes.

The default _render_dom() method simply places the outer node of the child widgets as the content of this DOM node, while preserving nodes that do not represent a widget. Overload as needed.

apply_style(style)

action – Apply CSS style to this widget object. e.g. "background: #f00; color: #0f0;". If the given value is a dict, its key-value pairs are converted to a CSS style string.

Initial styling can also be given in a property-like fashion: MyWidget(style='background:red;')

For static styling it is often better to define a CSS class attribute and/or use css_class.

capture_mouse

IntProp – To what extend the mouse is “captured”.

  • If 0, the mouse is not captured, and move events are only emitted when the mouse is pressed down (not recommended).
  • If 1 (default) the mouse is captured when pressed down, so move and up events are received also when the mouse is outside the widget.
  • If 2, move events are also emitted when the mouse is not pressed down and inside the widget.
check_real_size()

action – Check whether the current size has changed. It should usually not be necessary to invoke this action, since a widget does so by itself, but it some situations the widget may not be aware of possible size changes.

children

LocalProperty – The child widgets of this widget. This property is not settable and only present in JavaScript.

container

StringProp – The id of the DOM element that contains this widget if parent is None. Use ‘body’ to make this widget the root.

css_class

StringProp – The extra CSS class name to asign to the DOM element. Spaces can be used to delimit multiple names. Note that the DOM element already has a css class-name corresponding to its class (e.g. ‘flx-Widget) and all its superclasses.

dispose()

Overloaded version of dispose() that disposes any child widgets.

flex

FloatPairProp – How much space this widget takes (relative to the other widgets) when contained in a flexible layout such as HBox, HFix, HSplit or FormLayout. A flex of 0 means to take the minimum size. Flex is a two-element tuple, but both values can be specified at once by specifying a scalar.

icon

LocalProperty – The icon for this widget. This is used is some widgets classes, and is used as the app’s icon if this is the main widget. It is settable from Python, but only present in JavaScript.

init()

Overload this to initialize a custom widget. It’s preferred to use this instead of __init__(), because it gets called at a better moment in the instantiation of the widget.

This method receives any positional arguments that were passed to the constructor. When called, this widget is the current parent.

key_down(e)

emitter – Event emitted when a key is pressed down while this widget has focus. A key event has the following attributes:

  • key: the character corresponding to the key being pressed, or
    a key name like “Escape”, “Alt”, “Enter”.
  • modifiers: list of strings “Alt”, “Shift”, “Ctrl”, “Meta” for
    modifier keys pressed down at the time of the event.

A browser may associate certain actions with certain key presses. If this browser action is unwanted, it can be disabled by overloading this emitter:

@event.emitter
def key_down(self, e):
    # Prevent browser's default reaction to function keys
    ev = super().key_press(e)
    if ev.key.startswith('F'):
        e.preventDefault()
    return ev
key_press(e)

emitter – Event emitted when a key is released after pressing down, in theory. In contast to key_down, this event does not fire for the pressing of modifier keys, and some browsers will also not fire for the arrow keys, backspace, etc. See key_down for details.

key_up(e)

emitter – Event emitted when a key is released while this widget has focus. See key_down for details.

maxsize

FloatPairProp – The user-defined maximum size (width, height) of this widget in pixels. Note that using “max-width” or “max-height” in apply_style(). (and in the style kwarg) also set this property. Maximum sizes set in CSS are ignored.

minsize

FloatPairProp – The user-defined minimum size (width, height) of this widget in pixels. The default value differs per widget (Widget.DEFAULT_MIN_SIZE). Note that using “min-width” or “min-height” in apply_style(). (and in the style kwarg) also set this property. Minimum sizes set in CSS are ignored.

minsize_from_children

BoolProp – Whether the children are taken into account to calculate this widget’s size constraints. Default True: both the minsize of this widget and the size constraints of its children (plus spacing and padding for layout widgets) are used to calculate the size constraints for this widget.

Set to False to prevent the content in this widget to affect the parent’s layout, e.g. to allow fully collapsing this widget when the parent is a splitter. If this widget has a lot of content, you may want to combine with style='overflow-y: auto'.

parent

ComponentProp – The parent widget, or None if it has no parent. Setting this property will update the “children” property of the old and new parent.

pointer_cancel(e)

emitter – Event emitted when the mouse/touch is lost, e.g. the window becomes inactive during a drag. This only seem to work well for touch events in most browsers.

See pointer_down() for a description of the event object.

pointer_click(e)

emitter – Event emitted when mouse-button/touchpad/screen is clicked.

See pointer_down() for a description of the event object.

pointer_double_click(e)

emitter – Event emitted when mouse-button/touchpad/screen is double-clicked.

See pointer_down() for a description of the event object.

pointer_down(e)

emitter – Event emitted when mouse-button/touchpad/screen is pressed.

All pointer events have the following attributes:

  • pos: the pointer position, in pixels, relative to this widget
  • page_pos: the pointer position relative to the page
  • button: what mouse button the event is about, 1, 2, 3 are left, right,
    middle, respectively. 0 indicates no button.
  • buttons: what buttons were pressed at the time of the event.
  • modifiers: list of strings “Alt”, “Shift”, “Ctrl”, “Meta” for
    modifier keys pressed down at the time of the event.
  • touches: a dictionary that maps touch_id’s to (x, y, force) tuples.
    For mouse events touch_id is -1 and force is 1.

A note about the relation with JavaScript events: although the name might suggest that this makes use of JS pointer events, this is not the case; Flexx captures both mouse events and touch events and exposes both as its own “pointer event”. In effect, it works better on mobile devices, and has multi-touch support.

pointer_move(e)

emitter – Event fired when the mouse or a touch is moved.

See pointer_down for details.

pointer_up(e)

emitter – Event emitted when mouse-button/touchpad/screen is released.

See pointer_down() for a description of the event object.

pointer_wheel(e)

emitter – Event emitted when the mouse wheel is used.

See pointer_down() for a description of the event object. Additional event attributes:

  • hscroll: amount of scrolling in horizontal direction
  • vscroll: amount of scrolling in vertical direction
set_capture_mouse(*val)

action – Setter for the ‘capture_mouse’ property.

set_container(*val)

action – Setter for the ‘container’ property.

set_css_class(*val)

action – Setter for the ‘css_class’ property.

set_flex(*val)

action – Setter for the ‘flex’ property.

set_icon(val)

action – Set the icon for this widget. This is used is some widgets classes, and is used as the app’s icon if this is the main widget. It is settable from Python, but the property is not available in Python.

Can be a url, a relative url to a shared asset, or a base64 encoded image. In the future this may also support names in icon packs like FontAwesome.

set_maxsize(*val)

action – Setter for the ‘maxsize’ property.

set_minsize(*val)

action – Setter for the ‘minsize’ property.

set_minsize_from_children(*val)

action – Setter for the ‘minsize_from_children’ property.

set_parent(parent, pos=None)

action – Set the parent widget (can be None). This action also mutates the childen of the old and new parent.

set_tabindex(*val)

action – Setter for the ‘tabindex’ property.

set_title(*val)

action – Setter for the ‘title’ property.

size

FloatPairProp – The actual size of the widget (readonly). Flexx tries to keep this value up-to-date, but in e.g. a box layout, a change in a Button’s text can change the size of sibling widgets.

tabindex

IntProp – The index used to determine widget order when the user iterates through the widgets using tab. This also determines whether a widget is able to receive key events. Flexx automatically sets this property when it should emit key events. Effect of possible values on underlying DOM element:

  • -2: element cannot have focus unless its a special element like
    a link or form control (default).
  • -1: element can have focus, but is not reachable via tab.
  • 0: element can have focus, and is reachable via tab in the order
    at which the element is defined.
  • 1 and up: element can have focus, and the tab-order is determined
    by the value of tabindex.
title

StringProp – The string title of this widget. This is used to mark the widget in e.g. a tab layout or form layout, and is used as the app’s title if this is the main widget.