Widget Classes

Widget Base Classes

Widget

class urwid.Widget

Widget base class

__metaclass__ = urwid.WidgetMeta

See urwid.WidgetMeta definition

_selectable = False

The default selectable() method returns this value.

_sizing = frozenset(['flow', 'box', 'fixed'])

The default sizing() method returns this value.

_command_map = urwid.command_map

A shared CommandMap instance. May be redefined in subclasses or widget instances.

render(size, focus=False)

Note

This method is not implemented in Widget but must be implemented by any concrete subclass

Parameters:
  • size (widget size) –

    One of the following, maxcol and maxrow are integers > 0:

    (maxcol, maxrow)
    for box sizing – the parent chooses the exact size of this widget
    (maxcol,)
    for flow sizing – the parent chooses only the number of columns for this widget
    ()
    for fixed sizing – this widget is a fixed size which can’t be adjusted by the parent
  • focus (bool) – set to True if this widget or one of its children is in focus
Returns:

A Canvas subclass instance containing the rendered content of this widget

Text widgets return a TextCanvas (arbitrary text and display attributes), SolidFill widgets return a SolidCanvas (a single character repeated across the whole surface) and container widgets return a CompositeCanvas (one or more other canvases arranged arbitrarily).

If focus is False, the returned canvas may not have a cursor position set.

There is some metaclass magic defined in the Widget metaclass WidgetMeta that causes the result of this method to be cached by CanvasCache. Later calls will automatically look up the value in the cache first.

As a small optimization the class variable ignore_focus may be defined and set to True if this widget renders the same canvas regardless of the value of the focus parameter.

Any time the content of a widget changes it should call _invalidate() to remove any cached canvases, or the widget may render the cached canvas instead of creating a new one.

rows(size, focus=False)

Note

This method is not implemented in Widget but must be implemented by any flow widget. See sizing().

See Widget.render() for parameter details.

Returns:The number of rows required for this widget given a number of columns in size

This is the method flow widgets use to communicate their size to other widgets without having to render a canvas. This should be a quick calculation as this function may be called a number of times in normal operation. If your implementation may take a long time you should add your own caching here.

There is some metaclass magic defined in the Widget metaclass WidgetMeta that causes the result of this function to be retrieved from any canvas cached by CanvasCache, so if your widget has been rendered you may not receive calls to this function. The class variable ignore_focus may be defined and set to True if this widget renders the same size regardless of the value of the focus parameter.

keypress(size, key)

Note

This method is not implemented in Widget but must be implemented by any selectable widget. See selectable().

Parameters:
Returns:

None if key was handled by this widget or key (the same value passed) if key was not handled by this widget

Container widgets will typically call the keypress() method on whichever of their children is set as the focus.

The standard widgets use _command_map to determine what action should be performed for a given key. You may modify these values to your liking globally, at some level in the widget hierarchy or on individual widgets. See CommandMap for the defaults.

In your own widgets you may use whatever logic you like: filtering or translating keys, selectively passing along events etc.

mouse_event(size, event, button, col, row, focus)

Note

This method is not implemented in Widget but may be implemented by a subclass. Not implementing this method is equivalent to having a method that always returns False.

Parameters:
  • size (widget size) – See Widget.render() for details.
  • event (mouse event) – Values such as 'mouse press', 'ctrl mouse press', 'mouse release', 'meta mouse release', 'mouse drag'; see Mouse Input
  • button (int) – 1 through 5 for press events, often 0 for release events (which button was released is often not known)
  • col (int) – Column of the event, 0 is the left edge of this widget
  • row (int) – Row of the event, 0 it the top row of this widget
  • focus (bool) – Set to True if this widget or one of its children is in focus
Returns:

True if the event was handled by this widget, False otherwise

Container widgets will typically call the mouse_event() method on whichever of their children is at the position (col, row).

get_cursor_coords(size)

Note

This method is not implemented in Widget but must be implemented by any widget that may return cursor coordinates as part of the canvas that render() returns.

Parameters:size (widget size) – See Widget.render() for details.
Returns:(col, row) if this widget has a cursor, None otherwise

Return the cursor coordinates (col, row) of a cursor that will appear as part of the canvas rendered by this widget when in focus, or None if no cursor is displayed.

The ListBox widget uses this method to make sure a cursor in the focus widget is not scrolled out of view. It is a separate method to avoid having to render the whole widget while calculating layout.

Container widgets will typically call the get_cursor_coords() method on their focus widget.

get_pref_col(size)

Note

This method is not implemented in Widget but may be implemented by a subclass.

Parameters:size (widget size) – See Widget.render() for details.
Returns:a column number or 'left' for the leftmost available column or 'right' for the rightmost available column

Return the preferred column for the cursor to be displayed in this widget. This value might not be the same as the column returned from get_cursor_coords().

The ListBox and Pile widgets call this method on a widget losing focus and use the value returned to call move_cursor_to_coords() on the widget becoming the focus. This allows the focus to move up and down through widgets while keeping the cursor in approximately the same column on screen.

move_cursor_to_coords(size, col, row)

Note

This method is not implemented in Widget but may be implemented by a subclass. Not implementing this method is equivalent to having a method that always returns False.

Parameters:
  • size (widget size) – See Widget.render() for details.
  • col (int) – new column for the cursor, 0 is the left edge of this widget
  • row (int) – new row for the cursor, 0 it the top row of this widget
Returns:

True if the position was set successfully anywhere on row, False otherwise

_emit(name, *args)

Convenience function to emit signals with self as first argument.

_invalidate()

Mark cached canvases rendered by this widget as dirty so that they will not be used again.

base_widget

Read-only property that steps through decoration widgets and returns the one at the base. This default implementation returns self.

focus

Read-only property returning the child widget in focus for container widgets. This default implementation always returns None, indicating that this widget has no children.

focus_position

Property for reading and setting the focus position for container widgets. This default implementation raises IndexError, making normal widgets fail the same way accessing focus_position on an empty container widget would.

pack(size, focus=False)

See Widget.render() for parameter details.

Returns:A “packed” size (maxcol, maxrow) for this widget

Calculate and return a minimum size where all content could still be displayed. Fixed widgets must implement this method and return their size when () is passed as the size parameter.

This default implementation returns the size passed, or the maxcol passed and the value of rows() as the maxrow when (maxcol,) is passed as the size parameter.

Note

This is a new method that hasn’t been fully implemented across the standard widget types. In particular it has not yet been implemented for container widgets.

Text widgets have implemented this method. You can use Text.pack() to calculate the minumum columns and rows required to display a text widget without wrapping, or call it iteratively to calculate the minimum number of columns required to display the text wrapped into a target number of rows.

selectable()
Returns:True if this is a widget that is designed to take the focus, i.e. it contains something the user might want to interact with, False otherwise,

This default implementation returns _selectable. Subclasses may leave these is if the are not selectable, or if they are always selectable they may set the _selectable class variable to True.

If this method returns True then the keypress() method must be implemented.

Returning False does not guarantee that this widget will never be in focus, only that this widget will usually be skipped over when changing focus. It is still possible for non selectable widgets to have the focus (typically when there are no other selectable widgets visible).

sizing()
Returns:A frozenset including one or more of 'box', 'flow' and 'fixed'. Default implementation returns the value of _sizing, which for this class includes all three.

The sizing modes returned indicate the modes that may be supported by this widget, but is not sufficient to know that using that sizing mode will work. Subclasses should make an effort to remove sizing modes they know will not work given the state of the widget, but many do not yet do this.

If a sizing mode is missing from the set then the widget should fail when used in that mode.

If 'flow' is among the values returned then the other methods in this widget must be able to accept a single-element tuple (maxcol,) to their size parameter, and the rows() method must be defined.

If 'box' is among the values returned then the other methods must be able to accept a two-element tuple (maxcol, maxrow) to their size paramter.

If 'fixed' is among the values returned then the other methods must be able to accept an empty tuple () to their size parameter, and the pack() method must be defined.

WidgetWrap

class urwid.WidgetWrap(w)

w – widget to wrap, stored as self._w

This object will pass the functions defined in Widget interface definition to self._w.

The purpose of this widget is to provide a base class for widgets that compose other widgets for their display and behaviour. The details of that composition should not affect users of the subclass. The subclass may decide to expose some of the wrapped widgets by behaving like a ContainerWidget or WidgetDecoration, or it may hide them from outside access.

WidgetDecoration

class urwid.WidgetDecoration(original_widget)

original_widget – the widget being decorated

This is a base class for decoration widgets, widgets that contain one or more widgets and only ever have a single focus. This type of widget will affect the display or behaviour of the original_widget but it is not part of determining a chain of focus.

Don’t actually do this – use a WidgetDecoration subclass instead, these are not real widgets:

>>> WidgetDecoration(Text(u"hi"))
<WidgetDecoration flow widget <Text flow widget 'hi'>>
base_widget

Return the widget without decorations. If there is only one Decoration then this is the same as original_widget.

>>> t = Text('hello')
>>> wd1 = WidgetDecoration(t)
>>> wd2 = WidgetDecoration(wd1)
>>> wd3 = WidgetDecoration(wd2)
>>> wd3.original_widget is wd2
True
>>> wd3.base_widget is t
True

WidgetContainerMixin

class urwid.WidgetContainerMixin

Mixin class for widget containers implementing common container methods

get_focus_path()

Return the .focus_position values starting from this container and proceeding along each child widget until reaching a leaf (non-container) widget.

get_focus_widgets()

Return the .focus values starting from this container and proceeding along each child widget until reaching a leaf (non-container) widget.

Note that the list does not contain the topmost container widget (i.e, on which this method is called), but does include the lowest leaf widget.

set_focus_path(positions)

Set the .focus_position property starting from this container widget and proceeding along newly focused child widgets. Any failed assignment due do incompatible position types or invalid positions will raise an IndexError.

This method may be used to restore a particular widget to the focus by passing in the value returned from an earlier call to get_focus_path().

positions – sequence of positions

Basic Widget Classes

Text

class urwid.Text(markup, align='left', wrap='space', layout=None)

a horizontally resizeable text widget

Parameters:
  • markup (Text Markup) –

    content of text widget, one of:

    bytes or unicode
    text to be displayed
    (display attribute, text markup)
    text markup with display attribute applied to all parts of text markup with no display attribute already applied
    [text markup, text markup, ... ]
    all text markup in the list joined together
  • align (text alignment mode) – typically 'left', 'center' or 'right'
  • wrap (text wrapping mode) – typically 'space', 'any' or 'clip'
  • layout (text layout instance) – defaults to a shared StandardTextLayout instance
>>> Text(u"Hello")
<Text flow widget 'Hello'>
>>> t = Text(('bold', u"stuff"), 'right', 'any')
>>> t
<Text flow widget 'stuff' align='right' wrap='any'>
>>> print t.text
stuff
>>> t.attrib
[('bold', 5)]
attrib

Read-only property returning the run-length encoded display attributes of this widget

get_line_translation(maxcol, ta=None)

Return layout structure used to map self.text to a canvas. This method is used internally, but may be useful for debugging custom layout classes.

Parameters:
  • maxcol (int) – columns available for display
  • ta (text and display attributes) – None or the (text, display attributes) tuple returned from get_text()
get_text()
Returns:(text, display attributes)
text
complete bytes/unicode content of text widget
display attributes
run length encoded display attributes for text, eg. [('attr1', 10), ('attr2', 5)]
>>> Text(u"Hello").get_text() # ... = u in Python 2
(...'Hello', [])
>>> Text(('bright', u"Headline")).get_text()
(...'Headline', [('bright', 8)])
>>> Text([('a', u"one"), u"two", ('b', u"three")]).get_text()
(...'onetwothree', [('a', 3), (None, 3), ('b', 5)])
pack(size=None, focus=False)

Return the number of screen columns and rows required for this Text widget to be displayed without wrapping or clipping, as a single element tuple.

Parameters:size (widget size) – None for unlimited screen columns or (maxcol,) to specify a maximum column size
>>> Text(u"important things").pack()
(16, 1)
>>> Text(u"important things").pack((15,))
(9, 2)
>>> Text(u"important things").pack((8,))
(8, 2)
render(size, focus=False)

Render contents with wrapping and alignment. Return canvas.

See Widget.render() for parameter details.

>>> Text(u"important things").render((18,)).text # ... = b in Python 3
[...'important things  ']
>>> Text(u"important things").render((11,)).text
[...'important  ', ...'things     ']
rows(size, focus=False)

Return the number of rows the rendered text requires.

See Widget.rows() for parameter details.

>>> Text(u"important things").rows((18,))
1
>>> Text(u"important things").rows((11,))
2
set_align_mode(mode)

Set text alignment mode. Supported modes depend on text layout object in use but defaults to a StandardTextLayout instance

Parameters:mode (text alignment mode) – typically 'left', 'center' or 'right'
>>> t = Text(u"word")
>>> t.set_align_mode('right')
>>> t.align
'right'
>>> t.render((10,)).text # ... = b in Python 3
[...'      word']
>>> t.align = 'center'
>>> t.render((10,)).text
[...'   word   ']
>>> t.align = 'somewhere'
Traceback (most recent call last):
TextError: Alignment mode 'somewhere' not supported.
set_layout(align, wrap, layout=None)

Set the text layout object, alignment and wrapping modes at the same time.

Parameters:
  • wrap (text wrapping mode) – typically ‘space’, ‘any’ or ‘clip’
  • layout (text layout instance) – defaults to a shared StandardTextLayout instance
>>> t = Text(u"hi")
>>> t.set_layout('right', 'clip')
>>> t
<Text flow widget 'hi' align='right' wrap='clip'>
set_text(markup)

Set content of text widget.

Parameters:markup (text markup) – see Text for description.
>>> t = Text(u"foo")
>>> print t.text
foo
>>> t.set_text(u"bar")
>>> print t.text
bar
>>> t.text = u"baz"  # not supported because text stores text but set_text() takes markup
Traceback (most recent call last):
AttributeError: can't set attribute
set_wrap_mode(mode)

Set text wrapping mode. Supported modes depend on text layout object in use but defaults to a StandardTextLayout instance

Parameters:mode (text wrapping mode) – typically 'space', 'any' or 'clip'
>>> t = Text(u"some words")
>>> t.render((6,)).text # ... = b in Python 3
[...'some  ', ...'words ']
>>> t.set_wrap_mode('clip')
>>> t.wrap
'clip'
>>> t.render((6,)).text
[...'some w']
>>> t.wrap = 'any'  # Urwid 0.9.9 or later
>>> t.render((6,)).text
[...'some w', ...'ords  ']
>>> t.wrap = 'somehow'
Traceback (most recent call last):
TextError: Wrap mode 'somehow' not supported.
text

Read-only property returning the complete bytes/unicode content of this widget

Edit

class urwid.Edit(caption=u'', edit_text=u'', multiline=False, align='left', wrap='space', allow_tab=False, edit_pos=None, layout=None, mask=None)

Text editing widget implements cursor movement, text insertion and deletion. A caption may prefix the editing area. Uses text class for text layout.

Users of this class to listen for "change" events sent when the value of edit_text changes. See :func:connect_signal.

Parameters:
  • caption (text markup) – markup for caption preceeding edit_text, see Text for description of text markup.
  • edit_text (bytes or unicode) – initial text for editing, type (bytes or unicode) must match the text in the caption
  • multiline (bool) – True: ‘enter’ inserts newline False: return it
  • align (text alignment mode) – typically ‘left’, ‘center’ or ‘right’
  • wrap (text wrapping mode) – typically ‘space’, ‘any’ or ‘clip’
  • allow_tab (bool) – True: ‘tab’ inserts 1-8 spaces False: return it
  • edit_pos (int) – initial position for cursor, None:end of edit_text
  • layout (text layout instance) – defaults to a shared StandardTextLayout instance
  • mask (bytes or unicode) – hide text entered with this character, None:disable mask
>>> Edit()
<Edit selectable flow widget '' edit_pos=0>
>>> Edit(u"Y/n? ", u"yes")
<Edit selectable flow widget 'yes' caption='Y/n? ' edit_pos=3>
>>> Edit(u"Name ", u"Smith", edit_pos=1)
<Edit selectable flow widget 'Smith' caption='Name ' edit_pos=1>
>>> Edit(u"", u"3.14", align='right')
<Edit selectable flow widget '3.14' align='right' edit_pos=4>
edit_text

Read-only property returning the edit text for this widget.

get_cursor_coords(size)

Return the (x, y) coordinates of cursor within widget.

>>> Edit("? ","yes").get_cursor_coords((10,))
(5, 0)
get_edit_text()

Return the edit text for this widget.

>>> e = Edit(u"What? ", u"oh, nothing.")
>>> print e.get_edit_text()
oh, nothing.
>>> print e.edit_text
oh, nothing.
get_pref_col(size)

Return the preferred column for the cursor, or the current cursor x value. May also return 'left' or 'right' to indicate the leftmost or rightmost column available.

This method is used internally and by other widgets when moving the cursor up or down between widgets so that the column selected is one that the user would expect.

>>> size = (10,)
>>> Edit().get_pref_col(size)
0
>>> e = Edit(u"", u"word")
>>> e.get_pref_col(size)
4
>>> e.keypress(size, 'left')
>>> e.get_pref_col(size)
3
>>> e.keypress(size, 'end')
>>> e.get_pref_col(size)
'right'
>>> e = Edit(u"", u"2\nwords")
>>> e.keypress(size, 'left')
>>> e.keypress(size, 'up')
>>> e.get_pref_col(size)
4
>>> e.keypress(size, 'left')
>>> e.get_pref_col(size)
0
get_text()

Returns (text, display attributes). See Text.get_text() for details.

Text returned includes the caption and edit_text, possibly masked.

>>> Edit(u"What? ","oh, nothing.").get_text() # ... = u in Python 2
(...'What? oh, nothing.', [])
>>> Edit(('bright',u"user@host:~$ "),"ls").get_text()
(...'user@host:~$ ls', [('bright', 13)])
>>> Edit(u"password:", u"seekrit", mask=u"*").get_text()
(...'password:*******', [])
insert_text(text)

Insert text at the cursor position and update cursor. This method is used by the keypress() method when inserting one or more characters into edit_text.

Parameters:text (bytes or unicode) – text for inserting, type (bytes or unicode) must match the text in the caption
>>> e = Edit(u"", u"42")
>>> e.insert_text(u".5")
>>> e
<Edit selectable flow widget '42.5' edit_pos=4>
>>> e.set_edit_pos(2)
>>> e.insert_text(u"a")
>>> print e.edit_text
42a.5
insert_text_result(text)

Return result of insert_text(text) without actually performing the insertion. Handy for pre-validation.

Parameters:text (bytes or unicode) – text for inserting, type (bytes or unicode) must match the text in the caption
keypress(size, key)

Handle editing keystrokes, return others.

>>> e, size = Edit(), (20,)
>>> e.keypress(size, 'x')
>>> e.keypress(size, 'left')
>>> e.keypress(size, '1')
>>> print e.edit_text
1x
>>> e.keypress(size, 'backspace')
>>> e.keypress(size, 'end')
>>> e.keypress(size, '2')
>>> print e.edit_text
x2
>>> e.keypress(size, 'shift f1')
'shift f1'
mouse_event(size, event, button, x, y, focus)

Move the cursor to the location clicked for button 1.

>>> size = (20,)
>>> e = Edit("","words here")
>>> e.mouse_event(size, 'mouse press', 1, 2, 0, True)
True
>>> e.edit_pos
2
move_cursor_to_coords(size, x, y)

Set the cursor position with (x,y) coordinates. Returns True if move succeeded, False otherwise.

>>> size = (10,)
>>> e = Edit("","edit\ntext")
>>> e.move_cursor_to_coords(size, 5, 0)
True
>>> e.edit_pos
4
>>> e.move_cursor_to_coords(size, 5, 3)
False
>>> e.move_cursor_to_coords(size, 0, 1)
True
>>> e.edit_pos
5
position_coords(maxcol, pos)

Return (x, y) coordinates for an offset into self.edit_text.

render(size, focus=False)

Render edit widget and return canvas. Include cursor when in focus.

>>> c = Edit("? ","yes").render((10,), focus=True)
>>> c.text # ... = b in Python 3
[...'? yes     ']
>>> c.cursor
(5, 0)
set_caption(caption)

Set the caption markup for this widget.

Parameters:caption – markup for caption preceeding edit_text, see Text.__init__() for description of text markup.
>>> e = Edit("")
>>> e.set_caption("cap1")
>>> print e.caption
cap1
>>> e.set_caption(('bold', "cap2"))
>>> print e.caption
cap2
>>> e.attrib
[('bold', 4)]
>>> e.caption = "cap3"  # not supported because caption stores text but set_caption() takes markup
Traceback (most recent call last):
AttributeError: can't set attribute
set_edit_pos(pos)

Set the cursor position with a self.edit_text offset. Clips pos to [0, len(edit_text)].

Parameters:pos (int) – cursor position
>>> e = Edit(u"", u"word")
>>> e.edit_pos
4
>>> e.set_edit_pos(2)
>>> e.edit_pos
2
>>> e.edit_pos = -1  # Urwid 0.9.9 or later
>>> e.edit_pos
0
>>> e.edit_pos = 20
>>> e.edit_pos
4
set_edit_text(text)

Set the edit text for this widget.

Parameters:text (bytes or unicode) – text for editing, type (bytes or unicode) must match the text in the caption
>>> e = Edit()
>>> e.set_edit_text(u"yes")
>>> print e.edit_text
yes
>>> e
<Edit selectable flow widget 'yes' edit_pos=0>
>>> e.edit_text = u"no"  # Urwid 0.9.9 or later
>>> print e.edit_text
no
set_mask(mask)

Set the character for masking text away.

Parameters:mask (bytes or unicode) – hide text entered with this character, None:disable mask
set_text(markup)

Not supported by Edit widget.

>>> Edit().set_text("test")
Traceback (most recent call last):
EditError: set_text() not supported.  Use set_caption() or set_edit_text() instead.
update_text()

No longer supported.

>>> Edit().update_text()
Traceback (most recent call last):
EditError: update_text() has been removed.  Use set_caption() or set_edit_text() instead.
valid_char(ch)

Filter for text that may be entered into this widget by the user

Parameters:ch (bytes or unicode) – character to be inserted

This implementation returns True for all printable characters.

IntEdit

class urwid.IntEdit(caption='', default=None)

Edit widget for integer values

caption – caption markup default – default edit value

>>> IntEdit(u"", 42)
<IntEdit selectable flow widget '42' edit_pos=2>
keypress(size, key)

Handle editing keystrokes. Remove leading zeros.

>>> e, size = IntEdit(u"", 5002), (10,)
>>> e.keypress(size, 'home')
>>> e.keypress(size, 'delete')
>>> print e.edit_text
002
>>> e.keypress(size, 'end')
>>> print e.edit_text
2
valid_char(ch)

Return true for decimal digits.

value()

Return the numeric value of self.edit_text.

>>> e, size = IntEdit(), (10,)
>>> e.keypress(size, '5')
>>> e.keypress(size, '1')
>>> e.value() == 51
True

Button

class urwid.Button(label, on_press=None, user_data=None)
Parameters:
  • label – markup for button label
  • on_press – shorthand for connect_signal() function call for a single callback
  • user_data – user_data for on_press

Signals supported: 'click'

Register signal handler with:

urwid.connect_signal(button, 'click', callback, user_data)

where callback is callback(button [,user_data]) Unregister signal handlers with:

urwid.disconnect_signal(button, 'click', callback, user_data)
>>> Button(u"Ok")
<Button selectable flow widget 'Ok'>
>>> b = Button("Cancel")
>>> b.render((15,), focus=True).text # ... = b in Python 3
[...'< Cancel      >']
get_label()

Return label text.

>>> b = Button(u"Ok")
>>> print b.get_label()
Ok
>>> print b.label
Ok
keypress(size, key)

Send ‘click’ signal on ‘activate’ command.

>>> assert Button._command_map[' '] == 'activate'
>>> assert Button._command_map['enter'] == 'activate'
>>> size = (15,)
>>> b = Button(u"Cancel")
>>> clicked_buttons = []
>>> def handle_click(button):
...     clicked_buttons.append(button.label)
>>> key = connect_signal(b, 'click', handle_click)
>>> b.keypress(size, 'enter')
>>> b.keypress(size, ' ')
>>> clicked_buttons # ... = u in Python 2
[...'Cancel', ...'Cancel']
label

Return label text.

>>> b = Button(u"Ok")
>>> print b.get_label()
Ok
>>> print b.label
Ok
mouse_event(size, event, button, x, y, focus)

Send ‘click’ signal on button 1 press.

>>> size = (15,)
>>> b = Button(u"Ok")
>>> clicked_buttons = []
>>> def handle_click(button):
...     clicked_buttons.append(button.label)
>>> key = connect_signal(b, 'click', handle_click)
>>> b.mouse_event(size, 'mouse press', 1, 4, 0, True)
True
>>> b.mouse_event(size, 'mouse press', 2, 4, 0, True) # ignored
False
>>> clicked_buttons # ... = u in Python 2
[...'Ok']
set_label(label)

Change the button label.

label – markup for button label

>>> b = Button("Ok")
>>> b.set_label(u"Yup yup")
>>> b
<Button selectable flow widget 'Yup yup'>

CheckBox

class urwid.CheckBox(label, state=False, has_mixed=False, on_state_change=None, user_data=None)
Parameters:
  • label – markup for check box label
  • state – False, True or “mixed”
  • has_mixed – True if “mixed” is a state to cycle through
  • on_state_change – shorthand for connect_signal() function call for a single callback
  • user_data – user_data for on_state_change

Signals supported: 'change'

Register signal handler with:

urwid.connect_signal(check_box, 'change', callback, user_data)

where callback is callback(check_box, new_state [,user_data]) Unregister signal handlers with:

urwid.disconnect_signal(check_box, 'change', callback, user_data)
>>> CheckBox(u"Confirm")
<CheckBox selectable flow widget 'Confirm' state=False>
>>> CheckBox(u"Yogourt", "mixed", True)
<CheckBox selectable flow widget 'Yogourt' state='mixed'>
>>> cb = CheckBox(u"Extra onions", True)
>>> cb
<CheckBox selectable flow widget 'Extra onions' state=True>
>>> cb.render((20,), focus=True).text # ... = b in Python 3
[...'[X] Extra onions    ']
get_label()

Return label text.

>>> cb = CheckBox(u"Seriously")
>>> print cb.get_label()
Seriously
>>> print cb.label
Seriously
>>> cb.set_label([('bright_attr', u"flashy"), u" normal"])
>>> print cb.label  #  only text is returned
flashy normal
get_state()

Return the state of the checkbox.

keypress(size, key)

Toggle state on ‘activate’ command.

>>> assert CheckBox._command_map[' '] == 'activate'
>>> assert CheckBox._command_map['enter'] == 'activate'
>>> size = (10,)
>>> cb = CheckBox('press me')
>>> cb.state
False
>>> cb.keypress(size, ' ')
>>> cb.state
True
>>> cb.keypress(size, ' ')
>>> cb.state
False
label

Return label text.

>>> cb = CheckBox(u"Seriously")
>>> print cb.get_label()
Seriously
>>> print cb.label
Seriously
>>> cb.set_label([('bright_attr', u"flashy"), u" normal"])
>>> print cb.label  #  only text is returned
flashy normal
mouse_event(size, event, button, x, y, focus)

Toggle state on button 1 press.

>>> size = (20,)
>>> cb = CheckBox("clickme")
>>> cb.state
False
>>> cb.mouse_event(size, 'mouse press', 1, 2, 0, True)
True
>>> cb.state
True
set_label(label)

Change the check box label.

label – markup for label. See Text widget for description of text markup.

>>> cb = CheckBox(u"foo")
>>> cb
<CheckBox selectable flow widget 'foo' state=False>
>>> cb.set_label(('bright_attr', u"bar"))
>>> cb
<CheckBox selectable flow widget 'bar' state=False>
set_state(state, do_callback=True)

Set the CheckBox state.

state – True, False or “mixed” do_callback – False to supress signal from this change

>>> changes = []
>>> def callback_a(cb, state, user_data):
...     changes.append("A %r %r" % (state, user_data))
>>> def callback_b(cb, state):
...     changes.append("B %r" % state)
>>> cb = CheckBox('test', False, False)
>>> key1 = connect_signal(cb, 'change', callback_a, "user_a")
>>> key2 = connect_signal(cb, 'change', callback_b)
>>> cb.set_state(True) # both callbacks will be triggered
>>> cb.state
True
>>> disconnect_signal(cb, 'change', callback_a, "user_a")
>>> cb.state = False
>>> cb.state
False
>>> cb.set_state(True)
>>> cb.state
True
>>> cb.set_state(False, False) # don't send signal
>>> changes
["A True 'user_a'", 'B True', 'B False', 'B True']
state

Return the state of the checkbox.

toggle_state()

Cycle to the next valid state.

>>> cb = CheckBox("3-state", has_mixed=True)
>>> cb.state
False
>>> cb.toggle_state()
>>> cb.state
True
>>> cb.toggle_state()
>>> cb.state
'mixed'
>>> cb.toggle_state()
>>> cb.state
False

RadioButton

class urwid.RadioButton(group, label, state='first True', on_state_change=None, user_data=None)
Parameters:
  • group – list for radio buttons in same group
  • label – markup for radio button label
  • state – False, True, “mixed” or “first True”
  • on_state_change – shorthand for connect_signal() function call for a single ‘change’ callback
  • user_data – user_data for on_state_change

This function will append the new radio button to group. “first True” will set to True if group is empty.

Signals supported: 'change'

Register signal handler with:

urwid.connect_signal(radio_button, 'change', callback, user_data)

where callback is callback(radio_button, new_state [,user_data]) Unregister signal handlers with:

urwid.disconnect_signal(radio_button, 'change', callback, user_data)
>>> bgroup = [] # button group
>>> b1 = RadioButton(bgroup, u"Agree")
>>> b2 = RadioButton(bgroup, u"Disagree")
>>> len(bgroup)
2
>>> b1
<RadioButton selectable flow widget 'Agree' state=True>
>>> b2
<RadioButton selectable flow widget 'Disagree' state=False>
>>> b2.render((15,), focus=True).text # ... = b in Python 3
[...'( ) Disagree   ']
set_state(state, do_callback=True)

Set the RadioButton state.

state – True, False or “mixed”

do_callback – False to supress signal from this change

If state is True all other radio buttons in the same button group will be set to False.

>>> bgroup = [] # button group
>>> b1 = RadioButton(bgroup, u"Agree")
>>> b2 = RadioButton(bgroup, u"Disagree")
>>> b3 = RadioButton(bgroup, u"Unsure")
>>> b1.state, b2.state, b3.state
(True, False, False)
>>> b2.set_state(True)
>>> b1.state, b2.state, b3.state
(False, True, False)
>>> def relabel_button(radio_button, new_state):
...     radio_button.set_label(u"Think Harder!")
>>> key = connect_signal(b3, 'change', relabel_button)
>>> b3
<RadioButton selectable flow widget 'Unsure' state=False>
>>> b3.set_state(True) # this will trigger the callback
>>> b3
<RadioButton selectable flow widget 'Think Harder!' state=True>
toggle_state()

Set state to True.

>>> bgroup = [] # button group
>>> b1 = RadioButton(bgroup, "Agree")
>>> b2 = RadioButton(bgroup, "Disagree")
>>> b1.state, b2.state
(True, False)
>>> b2.toggle_state()
>>> b1.state, b2.state
(False, True)
>>> b2.toggle_state()
>>> b1.state, b2.state
(False, True)

TreeWidget

class urwid.TreeWidget(node)

A widget representing something in a nested tree display.

first_child()

Return first child if expanded.

keypress(size, key)

Handle expand & collapse requests (non-leaf nodes)

last_child()

Return last child if expanded.

next_inorder()

Return the next TreeWidget depth first from this one.

prev_inorder()

Return the previous TreeWidget depth first from this one.

selectable()

Allow selection of non-leaf nodes so children may be (un)expanded

update_expanded_icon()

Update display widget text for parent widgets

SelectableIcon

class urwid.SelectableIcon(text, cursor_position=1)
Parameters:
  • text – markup for this widget; see Text for description of text markup
  • cursor_position – position the cursor will appear in the text when this widget is in focus

This is a text widget that is selectable. A cursor displayed at a fixed location in the text when in focus. This widget has no special handling of keyboard or mouse input.

get_cursor_coords(size)

Return the position of the cursor if visible. This method is required for widgets that display a cursor.

keypress(size, key)

No keys are handled by this widget. This method is required for selectable widgets.

render(size, focus=False)

Render the text content of this widget with a cursor when in focus.

>>> si = SelectableIcon(u"[!]")
>>> si
<SelectableIcon selectable flow widget '[!]'>
>>> si.render((4,), focus=True).cursor
(1, 0)
>>> si = SelectableIcon("((*))", 2)
>>> si.render((8,), focus=True).cursor
(2, 0)
>>> si.render((2,), focus=True).cursor
(0, 1)

Decoration Widget Classes

AttrMap

class urwid.AttrMap(w, attr_map, focus_map=None)

AttrMap is a decoration that maps one set of attributes to another. This object will pass all function calls and variable references to the wrapped widget.

Parameters:
  • w (widget) – widget to wrap (stored as self.original_widget)
  • attr_map (display attribute or dict) – attribute to apply to w, or dict of old display attribute: new display attribute mappings
  • focus_map (display attribute or dict) – attribute to apply when in focus or dict of old display attribute: new display attribute mappings; if None use attr
>>> AttrMap(Divider(u"!"), 'bright')
<AttrMap flow widget <Divider flow widget '!'> attr_map={None: 'bright'}>
>>> AttrMap(Edit(), 'notfocus', 'focus')
<AttrMap selectable flow widget <Edit selectable flow widget '' edit_pos=0> attr_map={None: 'notfocus'} focus_map={None: 'focus'}>
>>> size = (5,)
>>> am = AttrMap(Text(u"hi"), 'greeting', 'fgreet')
>>> am.render(size, focus=False).content().next() # ... = b in Python 3
[('greeting', None, ...'hi   ')]
>>> am.render(size, focus=True).content().next()
[('fgreet', None, ...'hi   ')]
>>> am2 = AttrMap(Text(('word', u"hi")), {'word':'greeting', None:'bg'})
>>> am2
<AttrMap flow widget <Text flow widget 'hi'> attr_map={'word': 'greeting', None: 'bg'}>
>>> am2.render(size).content().next()
[('greeting', None, ...'hi'), ('bg', None, ...'   ')]
render(size, focus=False)

Render wrapped widget and apply attribute. Return canvas.

set_attr_map(attr_map)

Set the attribute mapping dictionary {from_attr: to_attr, ...}

Note this function does not accept a single attribute the way the constructor does. You must specify {None: attribute} instead.

>>> w = AttrMap(Text(u"hi"), None)
>>> w.set_attr_map({'a':'b'})
>>> w
<AttrMap flow widget <Text flow widget 'hi'> attr_map={'a': 'b'}>
set_focus_map(focus_map)

Set the focus attribute mapping dictionary {from_attr: to_attr, ...}

If None this widget will use the attr mapping instead (no change when in focus).

Note this function does not accept a single attribute the way the constructor does. You must specify {None: attribute} instead.

>>> w = AttrMap(Text(u"hi"), {})
>>> w.set_focus_map({'a':'b'})
>>> w
<AttrMap flow widget <Text flow widget 'hi'> attr_map={} focus_map={'a': 'b'}>
>>> w.set_focus_map(None)
>>> w
<AttrMap flow widget <Text flow widget 'hi'> attr_map={}>

Padding

class urwid.Padding(w, align='left', width=('relative', 100), min_width=None, left=0, right=0)
Parameters:
  • w (Widget) – a box, flow or fixed widget to pad on the left and/or right this widget is stored as self.original_widget
  • align – one of: 'left', 'center', 'right' ('relative', percentage 0=left 100=right)
  • width

    one of:

    given width
    integer number of columns for self.original_widget
    'pack'
    try to pack self.original_widget to its ideal size
    ('relative', percentage of total width)
    make width depend on the container’s width
    'clip'
    to enable clipping mode for a fixed widget
  • min_width (int) – the minimum number of columns for self.original_widget or None
  • left (int) – a fixed number of columns to pad on the left
  • right (int) – a fixed number of columns to pad on the right

Clipping Mode: (width= 'clip') In clipping mode this padding widget will behave as a flow widget and self.original_widget will be treated as a fixed widget. self.original_widget will will be clipped to fit the available number of columns. For example if align is 'left' then self.original_widget may be clipped on the right.

>>> size = (7,)
>>> def pr(w):
...     for t in w.render(size).text:
...         print "|%s|" % (t.decode('ascii'),)
>>> pr(Padding(Text(u"Head"), ('relative', 20), 'pack'))
| Head  |
>>> pr(Padding(Divider(u"-"), left=2, right=1))
|  ---- |
>>> pr(Padding(Divider(u"*"), 'center', 3))
|  ***  |
>>> p=Padding(Text(u"1234"), 'left', 2, None, 1, 1)
>>> p
<Padding flow widget <Text flow widget '1234'> left=1 right=1 width=2>
>>> pr(p)   # align against left
| 12    |
| 34    |
>>> p.align = 'right'
>>> pr(p)   # align against right
|    12 |
|    34 |
>>> pr(Padding(Text(u"hi\nthere"), 'right', 'pack')) # pack text first
|  hi   |
|  there|
align

Return the padding alignment setting.

get_cursor_coords(size)

Return the (x,y) coordinates of cursor within self._original_widget.

get_pref_col(size)

Return the preferred column from self._original_widget, or None.

keypress(size, key)

Pass keypress to self._original_widget.

mouse_event(size, event, button, x, y, focus)

Send mouse event if position is within self._original_widget.

move_cursor_to_coords(size, x, y)

Set the cursor position with (x,y) coordinates of self._original_widget.

Returns True if move succeeded, False otherwise.

padding_values(size, focus)

Return the number of columns to pad on the left and right.

Override this method to define custom padding behaviour.

rows(size, focus=False)

Return the rows needed for self.original_widget.

width

Return the padding width.

Filler

class urwid.Filler(body, valign='middle', height='pack', min_height=None, top=0, bottom=0)
Parameters:
  • body (Widget) – a flow widget or box widget to be filled around (stored as self.original_widget)
  • valign – one of: 'top', 'middle', 'bottom', ('relative', percentage 0=top 100=bottom)
  • height

    one of:

    'pack'
    if body is a flow widget
    given height
    integer number of rows for self.original_widget
    ('relative', percentage of total height)
    make height depend on container’s height
  • min_height

    one of:

    None
    if no minimum or if body is a flow widget
    minimum height
    integer number of rows for the widget when height not fixed
  • top (int) – a fixed number of rows to fill at the top
  • bottom (int) – a fixed number of rows to fill at the bottom

If body is a flow widget then height must be 'flow' and min_height will be ignored.

Filler widgets will try to satisfy height argument first by reducing the valign amount when necessary. If height still cannot be satisfied it will also be reduced.

filler_values(size, focus)

Return the number of rows to pad on the top and bottom.

Override this method to define custom padding behaviour.

get_cursor_coords(size)

Return cursor coords from self.original_widget if any.

get_pref_col(size)

Return pref_col from self.original_widget if any.

keypress(size, key)

Pass keypress to self.original_widget.

mouse_event(size, event, button, col, row, focus)

Pass to self.original_widget.

move_cursor_to_coords(size, col, row)

Pass to self.original_widget.

render(size, focus=False)

Render self.original_widget with space above and/or below.

selectable()

Return selectable from body.

Divider

class urwid.Divider(div_char=u' ', top=0, bottom=0)

Horizontal divider widget

Parameters:
  • div_char (bytes or unicode) – character to repeat across line
  • top (int) – number of blank lines above
  • bottom (int) – number of blank lines below
>>> Divider()
<Divider flow widget>
>>> Divider(u'-')
<Divider flow widget '-'>
>>> Divider(u'x', 1, 2)
<Divider flow widget 'x' bottom=2 top=1>
render(size, focus=False)

Render the divider as a canvas and return it.

>>> Divider().render((10,)).text # ... = b in Python 3
[...'          ']
>>> Divider(u'-', top=1).render((10,)).text
[...'          ', ...'----------']
>>> Divider(u'x', bottom=2).render((5,)).text
[...'xxxxx', ...'     ', ...'     ']
rows(size, focus=False)

Return the number of lines that will be rendered.

>>> Divider().rows((10,))
1
>>> Divider(u'x', 1, 2).rows((10,))
4

LineBox

class urwid.LineBox(original_widget, title='', tlcorner=u'u250c', tline=u'u2500', lline=u'u2502', trcorner=u'u2510', blcorner=u'u2514', rline=u'u2502', bline=u'u2500', brcorner=u'u2518')

Draw a line around original_widget.

Use ‘title’ to set an initial title text with will be centered on top of the box.

You can also override the widgets used for the lines/corners:
tline: top line bline: bottom line lline: left line rline: right line tlcorner: top left corner trcorner: top right corner blcorner: bottom left corner brcorner: bottom right corner

SolidFill

class urwid.SolidFill(fill_char=' ')

A box widget that fills an area with a single character

Parameters:fill_char (bytes or unicode) – character to fill area with
>>> SolidFill(u'8')
<SolidFill box widget '8'>
render(size, focus=False)

Render the Fill as a canvas and return it.

>>> SolidFill().render((4,2)).text # ... = b in Python 3
[...'    ', ...'    ']
>>> SolidFill('#').render((5,3)).text
[...'#####', ...'#####', ...'#####']

PopUpLauncher

class urwid.PopUpLauncher(original_widget)
create_pop_up()

Subclass must override this method and return a widget to be used for the pop-up. This method is called once each time the pop-up is opened.

get_pop_up_parameters()

Subclass must override this method and have it return a dict, eg:

{‘left’:0, ‘top’:1, ‘overlay_width’:30, ‘overlay_height’:4}

This method is called each time this widget is rendered.

PopUpTarget

class urwid.PopUpTarget(original_widget)

WidgetPlaceholder

class urwid.WidgetPlaceholder(original_widget)

This is a do-nothing decoration widget that can be used for swapping between widgets without modifying the container of this widget.

This can be useful for making an interface with a number of distinct pages or for showing and hiding menu or status bars.

The widget displayed is stored as the self.original_widget property and can be changed by assigning a new widget to it.

WidgetDisable

class urwid.WidgetDisable(original_widget)

A decoration widget that disables interaction with the widget it wraps. This widget always passes focus=False to the wrapped widget, even if it somehow does become the focus.

Container Widget Classes

Frame

class urwid.Frame(body, header=None, footer=None, focus_part='body')

Frame widget is a box widget with optional header and footer flow widgets placed above and below the box widget.

Note

The main difference between a Frame and a Pile widget defined as: Pile([(‘pack’, header), body, (‘pack’, footer)]) is that the Frame will not automatically change focus up and down in response to keystrokes.

Parameters:
  • body (Widget) – a box widget for the body of the frame
  • header (Widget) – a flow widget for above the body (or None)
  • footer (Widget) – a flow widget for below the body (or None)
  • focus_part (str) – ‘header’, ‘footer’ or ‘body’
contents

a dict-like object similar to:

{
    'body': (body_widget, None),
    'header': (header_widget, None),  # if frame has a header
    'footer': (footer_widget, None) # if frame has a footer
}

This object may be used to read or update the contents of the Frame.

The values are similar to the list-like .contents objects used in other containers with (Widget, options) tuples, but are constrained to keys for each of the three usual parts of a Frame. When other keys are used a KeyError will be raised.

Currently all options are None, but using the options() method to create the options value is recommended for forwards compatibility.

focus

child Widget in focus: the body, header or footer widget. This is a read-only property.

focus_position

writeable property containing an indicator which part of the frame that is in focus: ‘body’, ‘header’ or ‘footer’.

frame_top_bottom(size, focus)

Calculate the number of rows for the header and footer.

Parameters:
  • size (widget size) – See Widget.render() for details
  • focus (bool) – True if this widget is in focus
Returns:

(head rows, foot rows),(orig head, orig foot) orig head/foot are from rows() calls.

Return type:

(int, int), (int, int)

get_focus()

Return an indicator which part of the frame is in focus

Note

included for backwards compatibility. You should rather use the container property focus_position to get this value.

Returns:one of ‘header’, ‘footer’ or ‘body’.
Return type:str
keypress(size, key)

Pass keypress to widget in focus.

mouse_event(size, event, button, col, row, focus)

Pass mouse event to appropriate part of frame. Focus may be changed on button 1 press.

options()

There are currently no options for Frame contents.

Return None as a placeholder for future options.

set_focus(part)

Determine which part of the frame is in focus.

Note

included for backwards compatibility. You should rather use the container property focus_position to set this value.

Parameters:part (str) – ‘header’, ‘footer’ or ‘body’

ListBox

class urwid.ListBox(body)

a horizontally stacked list of widgets

Parameters:body (ListWalker) – a ListWalker subclass such as SimpleFocusListWalker that contains widgets to be displayed inside the list box
calculate_visible(size, focus=False)

Returns the widgets that would be displayed in the ListBox given the current size and focus.

see Widget.render() for parameter details

Returns:(middle, top, bottom) or (None, None, None)
middle
(row offset*(when +ve) or *inset*(when -ve), *focus widget, focus position, focus rows, cursor coords or None)
top
(# lines to trim off top, list of (widget, position, rows) tuples above focus in order from bottom to top)
bottom
(# lines to trim off bottom, list of (widget, position, rows) tuples below focus in order from top to bottom)
change_focus(size, position, offset_inset=0, coming_from=None, cursor_coords=None, snap_rows=None)

Change the current focus widget. This is used internally by methods that know the widget’s size.

See also set_focus().

Parameters:
  • size – see Widget.render() for details
  • position – a position compatible with self.body.set_focus()
  • offset_inset (int) – either the number of rows between the top of the listbox and the start of the focus widget (+ve value) or the number of lines of the focus widget hidden off the top edge of the listbox (-ve value) or 0 if the top edge of the focus widget is aligned with the top edge of the listbox (default if unspecified)
  • coming_from (str) – either ‘above’, ‘below’ or unspecified None
  • cursor_coords ((int, int)) – (x, y) tuple indicating the desired column and row for the cursor, a (x,) tuple indicating only the column for the cursor, or unspecified
  • snap_rows (int) – the maximum number of extra rows to scroll when trying to “snap” a selectable focus into the view
contents

An object that allows reading widgets from the ListBox’s list walker as a (widget, options) tuple. None is currently the only value for options.

Warning

This object may not be used to set or iterate over contents.

You must use the list walker stored as body to perform manipulation and iteration, if supported.

ends_visible(size, focus=False)

Return a list that may contain 'top' and/or 'bottom'.

i.e. this function will return one of: [], ['top'], ['bottom'] or ['top', 'bottom'].

convenience function for checking whether the top and bottom of the list are visible

focus

the child widget in focus or None when ListBox is empty

focus_position

the position of child widget in focus. The valid values for this position depend on the list walker in use. IndexError will be raised by reading this property when the ListBox is empty or setting this property to an invalid position.

get_cursor_coords(size)

See Widget.get_cursor_coords() for details

get_focus()

Return a (focus widget, focus position) tuple, for backwards compatibility. You may also use the new standard container properties focus and focus_position to read these values.

get_focus_offset_inset(size)

Return (offset rows, inset rows) for focus widget.

keypress(size, key)

Move selection through the list elements scrolling when necessary. ‘up’ and ‘down’ are first passed to widget in focus in case that widget can handle them. ‘page up’ and ‘page down’ are always handled by the ListBox.

Keystrokes handled by this widget are:
‘up’ up one line (or widget) ‘down’ down one line (or widget) ‘page up’ move cursor up one listbox length ‘page down’ move cursor down one listbox length
make_cursor_visible(size)

Shift the focus widget so that its cursor is visible.

mouse_event(size, event, button, col, row, focus)

Pass the event to the contained widgets. May change focus on button 1 press.

options()

There are currently no options for ListBox contents.

Return None as a placeholder for future options.

render(size, focus=False)

Render ListBox and return canvas.

see Widget.render() for details

set_focus(position, coming_from=None)

Set the focus position and try to keep the old focus in view.

Parameters:
  • position – a position compatible with self.body.set_focus()
  • coming_from (str) – set to ‘above’ or ‘below’ if you know that old position is above or below the new position.
set_focus_valign(valign)

Set the focus widget’s display offset and inset.

Parameters:valign – one of: ‘top’, ‘middle’, ‘bottom’ (‘fixed top’, rows) (‘fixed bottom’, rows) (‘relative’, percentage 0=top 100=bottom)
shift_focus(size, offset_inset)

Move the location of the current focus relative to the top. This is used internally by methods that know the widget’s size.

See also set_focus_valign().

Parameters:
  • size – see Widget.render() for details
  • offset_inset (int) – either the number of rows between the top of the listbox and the start of the focus widget (+ve value) or the number of lines of the focus widget hidden off the top edge of the listbox (-ve value) or 0 if the top edge of the focus widget is aligned with the top edge of the listbox.
update_pref_col_from_focus(size)

Update self.pref_col from the focus widget.

TreeListBox

class urwid.TreeListBox(body)

A ListBox with special handling for navigation and collapsing of TreeWidgets

Parameters:body (ListWalker) – a ListWalker subclass such as SimpleFocusListWalker that contains widgets to be displayed inside the list box
collapse_focus_parent(size)

Collapse parent directory.

focus_end(size)

Move focus to far bottom.

focus_home(size)

Move focus to very top.

move_focus_to_parent(size)

Move focus to parent of widget in focus.

unhandled_input(size, input)

Handle macro-navigation keys

Columns

class urwid.Columns(widget_list, dividechars=0, focus_column=None, min_width=1, box_columns=None)

Widgets arranged horizontally in columns from left to right

Parameters:
  • widget_list – iterable of flow or box widgets
  • dividechars – number of blank characters between columns
  • focus_column – index into widget_list of column in focus, if None the first selectable widget will be chosen.
  • min_width – minimum width for each column which is not calling widget.pack() in widget_list.
  • box_columns – a list of column indexes containing box widgets whose height is set to the maximum of the rows required by columns not listed in box_columns.

widget_list may also contain tuples such as:

(given_width, widget)
make this column given_width screen columns wide, where given_width is an int
('pack', widget)
call pack() to calculate the width of this column
('weight', weight, widget)`
give this column a relative weight (number) to calculate its width from the screen columns remaining

Widgets not in a tuple are the same as ('weight', 1, widget)

If the Columns widget is treated as a box widget then all children are treated as box widgets, and box_columns is ignored.

If the Columns widget is treated as a flow widget then the rows are calculated as the largest rows() returned from all columns except the ones listed in box_columns. The box widgets in box_columns will be displayed with this calculated number of rows, filling the full height.

box_columns

A list of the indexes of the columns that are to be treated as box widgets when the Columns is treated as a flow widget.

Note

only for backwards compatibility. You should use the new standard container property contents.

column_types

A list of the old partial options values for widgets in this Pile, for backwards compatibility only. You should use the new standard container property .contents to modify Pile contents.

column_widths(size, focus=False)

Return a list of column widths.

0 values in the list mean hide corresponding column completely

contents

The contents of this Columns as a list of (widget, options) tuples. This list may be modified like a normal list and the Columns widget will update automatically.

See also

Create new options tuples with the options() method

focus

the child widget in focus or None when Columns is empty

focus_col

A property for reading and setting the index of the column in focus.

Note

only for backwards compatibility. You may also use the new standard container property focus_position to get the focus.

focus_position

index of child widget in focus. Raises IndexError if read when Columns is empty, or when set to an invalid index.

get_cursor_coords(size)

Return the cursor coordinates from the focus widget.

get_focus()

Return the widget in focus, for backwards compatibility. You may also use the new standard container property .focus to get the child widget in focus.

get_focus_column()

Return the focus column index.

Note

only for backwards compatibility. You may also use the new standard container property focus_position to get the focus.

get_pref_col(size)

Return the pref col from the column in focus.

has_flow_type

Deprecated since version 1.0: Read values from contents instead.

keypress(size, key)

Pass keypress to the focus column.

Parameters:size (int, int) – (maxcol,) if widget_list contains flow widgets or (maxcol, maxrow) if it contains box widgets.
mouse_event(size, event, button, col, row, focus)

Send event to appropriate column. May change focus on button 1 press.

move_cursor_to_coords(size, col, row)

Choose a selectable column to focus based on the coords.

see Widget.move_cursor_coords() for details

options(width_type='weight', width_amount=1, box_widget=False)

Return a new options tuple for use in a Pile’s .contents list.

This sets an entry’s width type: one of the following:

'pack'
Call the widget’s Widget.pack() method to determine how wide this column should be. width_amount is ignored.
'given'
Make column exactly width_amount screen-columns wide.
'weight'
Allocate the remaining space to this column by using width_amount as a weight value.
Parameters:
  • width_type'pack', 'given' or 'weight'
  • width_amountNone for 'pack', a number of screen columns for 'given' or a weight value (number) for 'weight'
  • box_widget (bool) – set to True if this widget is to be treated as a box widget when the Columns widget itself is treated as a flow widget.
render(size, focus=False)

Render columns and return canvas.

Parameters:
  • size – see Widget.render() for details
  • focus (bool) – True if this widget is in focus
rows(size, focus=False)

Return the number of rows required by the columns. This only makes sense if widget_list contains flow widgets.

see Widget.rows() for details

selectable()

Return the selectable value of the focus column.

set_focus(item)

Set the item in focus

Note

only for backwards compatibility. You may also use the new standard container property focus_position to get the focus.

Parameters:item – widget or integer index
set_focus_column(num)

Set the column in focus by its index in widget_list.

Parameters:num (int) – index of focus-to-be entry

Note

only for backwards compatibility. You may also use the new standard container property focus_position to set the focus.

widget_list

A list of the widgets in this Columns

Note

only for backwards compatibility. You should use the new standard container property contents.

Pile

class urwid.Pile(widget_list, focus_item=None)

A pile of widgets stacked vertically from top to bottom

Parameters:
  • widget_list (iterable) – child widgets
  • focus_item (Widget or int) – child widget that gets the focus initially. Chooses the first selectable widget if unset.

widget_list may also contain tuples such as:

(given_height, widget)
always treat widget as a box widget and give it given_height rows, where given_height is an int
('pack', widget)
allow widget to calculate its own height by calling its rows() method, ie. treat it as a flow widget.
('weight', weight, widget)
if the pile is treated as a box widget then treat widget as a box widget with a height based on its relative weight value, otherwise treat the same as ('pack', widget).

Widgets not in a tuple are the same as ('weight', 1, widget)`

Note

If the Pile is treated as a box widget there must be at least one 'weight' tuple in widget_list.

contents

The contents of this Pile as a list of (widget, options) tuples.

options currently may be one of

('pack', None)
allow widget to calculate its own height by calling its rows method, i.e. treat it as a flow widget.
('given', n)
Always treat widget as a box widget with a given height of n rows.
('weight', w)
If the Pile itself is treated as a box widget then the value w will be used as a relative weight for assigning rows to this box widget. If the Pile is being treated as a flow widget then this is the same as ('pack', None) and the w value is ignored.

If the Pile itself is treated as a box widget then at least one widget must have a ('weight', w) options value, or the Pile will not be able to grow to fill the required number of rows.

This list may be modified like a normal list and the Pile widget will updated automatically.

See also

Create new options tuples with the options() method

focus

the child widget in focus or None when Pile is empty

focus_item

A property for reading and setting the widget in focus.

Note

only for backwards compatibility. You should use the new standard container properties focus and focus_position to get the child widget in focus or modify the focus position.

focus_position

index of child widget in focus. Raises IndexError if read when Pile is empty, or when set to an invalid index.

get_cursor_coords(size)

Return the cursor coordinates of the focus widget.

get_focus()

Return the widget in focus, for backwards compatibility. You may also use the new standard container property .focus to get the child widget in focus.

get_item_rows(size, focus)

Return a list of the number of rows used by each widget in self.contents

get_item_size(size, i, focus, item_rows=None)

Return a size appropriate for passing to self.contents[i][0].render

get_pref_col(size)

Return the preferred column for the cursor, or None.

item_types

A list of the options values for widgets in this Pile.

Note

only for backwards compatibility. You should use the new standard container property contents.

keypress(size, key)

Pass the keypress to the widget in focus. Unhandled ‘up’ and ‘down’ keys may cause a focus change.

mouse_event(size, event, button, col, row, focus)

Pass the event to the contained widget. May change focus on button 1 press.

move_cursor_to_coords(size, col, row)

Capture pref col and set new focus.

options(height_type='weight', height_amount=1)

Return a new options tuple for use in a Pile’s contents list.

Parameters:
  • height_type'pack', 'given' or 'weight'
  • height_amountNone for 'pack', a number of rows for 'fixed' or a weight value (number) for 'weight'
selectable()

Return True if the focus item is selectable.

set_focus(item)

Set the item in focus, for backwards compatibility.

Note

only for backwards compatibility. You should use the new standard container property focus_position. to set the position by integer index instead.

Parameters:item (Widget or int) – element to focus
widget_list

A list of the widgets in this Pile

Note

only for backwards compatibility. You should use the new standard container property contents.

GridFlow

class urwid.GridFlow(cells, cell_width, h_sep, v_sep, align)

The GridFlow widget is a flow widget that renders all the widgets it contains the same width and it arranges them from left to right and top to bottom.

Parameters:
  • cells – list of flow widgets to display
  • cell_width – column width for each cell
  • h_sep – blank columns between each cell horizontally
  • v_sep – blank rows between cells vertically (if more than one row is required to display all the cells)
  • align – horizontal alignment of cells, one of: ‘left’, ‘center’, ‘right’, (‘relative’, percentage 0=left 100=right)
cell_width

The width of each cell in the GridFlow. Setting this value affects all cells.

cells

A list of the widgets in this GridFlow

Note

only for backwards compatibility. You should use the new use the new standard container property contents to modify GridFlow contents.

contents

The contents of this GridFlow as a list of (widget, options) tuples.

options is currently a tuple in the form (‘fixed’, number). number is the number of screen columns to allocate to this cell. ‘fixed’ is the only type accepted at this time.

This list may be modified like a normal list and the GridFlow widget will update automatically.

See also

Create new options tuples with the options() method.

focus

the child widget in focus or None when GridFlow is empty

focus_cell

The widget in focus, for backwards compatibility.

Note

only for backwards compatibility. You should use the new use the new standard container property focus to get the widget in focus and focus_position to get/set the cell in focus by index.

focus_position

index of child widget in focus. Raises IndexError if read when GridFlow is empty, or when set to an invalid index.

generate_display_widget(size)

Actually generate display widget (ignoring cache)

get_cursor_coords(size)

Get cursor from display widget.

get_display_widget(size)

Arrange the cells into columns (and possibly a pile) for display, input or to calculate rows, and update the display widget.

get_focus()

Return the widget in focus, for backwards compatibility.

Note

only for backwards compatibility. You may also use the new standard container property focus to get the focus.

get_pref_col(size)

Return pref col from display widget.

keypress(size, key)

Pass keypress to display widget for handling. Captures focus changes.

move_cursor_to_coords(size, col, row)

Set the widget in focus based on the col + row.

options(width_type='given', width_amount=None)

Return a new options tuple for use in a GridFlow’s .contents list.

width_type – ‘given’ is the only value accepted width_amount – None to use the default cell_width for this GridFlow

set_focus(cell)

Set the cell in focus, for backwards compatibility.

Note

only for backwards compatibility. You may also use the new standard container property focus_position to get the focus.

Parameters:cell (Widget or int) – contained element to focus

BoxAdapter

class urwid.BoxAdapter(box_widget, height)

Adapter for using a box widget where a flow widget would usually go

Create a flow widget that contains a box widget

Parameters:
  • box_widget (Widget) – box widget to wrap
  • height (int) – number of rows for box widget
>>> BoxAdapter(SolidFill(u"x"), 5) # 5-rows of x's
<BoxAdapter flow widget <SolidFill box widget 'x'> height=5>
rows(size, focus=False)

Return the predetermined height (behave like a flow widget)

>>> BoxAdapter(SolidFill(u"x"), 5).rows((20,))
5

Overlay

class urwid.Overlay(top_w, bottom_w, align, width, valign, height, min_width=None, min_height=None, left=0, right=0, top=0, bottom=0)

Overlay contains two box widgets and renders one on top of the other

Parameters:
  • top_w (Widget) – a flow, box or fixed widget to overlay “on top”
  • bottom_w (Widget) – a box widget to appear “below” previous widget
  • align (str) – alignment, one of 'left', 'center', 'right' or ('relative', percentage 0=left 100=right)
  • width

    width type, one of:

    'pack'
    if top_w is a fixed widget
    given width
    integer number of columns wide
    ('relative', percentage of total width)
    make top_w width related to container width
  • valign – alignment mode, one of 'top', 'middle', 'bottom' or ('relative', percentage 0=top 100=bottom)
  • height

    one of:

    'pack'
    if top_w is a flow or fixed widget
    given height
    integer number of rows high
    ('relative', percentage of total height)
    make top_w height related to container height
  • min_width (int) – the minimum number of columns for top_w when width is not fixed
  • min_height (int) – minimum number of rows for top_w when height is not fixed
  • left (int) – a fixed number of columns to add on the left
  • right (int) – a fixed number of columns to add on the right
  • top (int) – a fixed number of rows to add on the top
  • bottom (int) – a fixed number of rows to add on the bottom

Overlay widgets behave similarly to Padding and Filler widgets when determining the size and position of top_w. bottom_w is always rendered the full size available “below” top_w.

calculate_padding_filler(size, focus)

Return (padding left, right, filler top, bottom).

contents

a list-like object similar to:

[(bottom_w, bottom_options)),
 (top_w, top_options)]

This object may be used to read or update top and bottom widgets and top widgets’s options, but no widgets may be added or removed.

top_options takes the form (align_type, align_amount, width_type, width_amount, min_width, left, right, valign_type, valign_amount, height_type, height_amount, min_height, top, bottom)

bottom_options is always (‘left’, None, ‘relative’, 100, None, 0, 0, ‘top’, None, ‘relative’, 100, None, 0, 0) which means that bottom widget always covers the full area of the Overlay. writing a different value for bottom_options raises an OverlayError.

focus

the top widget in this overlay is always in focus

focus_position

index of child widget in focus, currently always 1

get_cursor_coords(size)

Return cursor coords from top_w, if any.

keypress(size, key)

Pass keypress to top_w.

mouse_event(size, event, button, col, row, focus)

Pass event to top_w, ignore if outside of top_w.

options(align_type, align_amount, width_type, width_amount, valign_type, valign_amount, height_type, height_amount, min_width=None, min_height=None, left=0, right=0, top=0, bottom=0)

Return a new options tuple for use in this Overlay’s .contents mapping.

This is the common container API to create options for replacing the top widget of this Overlay. It is provided for completeness but is not necessarily the easiest way to change the overlay parameters. See also set_overlay_parameters()

render(size, focus=False)

Render top_w overlayed on bottom_w.

selectable()

Return selectable from top_w.

set_overlay_parameters(align, width, valign, height, min_width=None, min_height=None, left=0, right=0, top=0, bottom=0)

Adjust the overlay size and position parameters.

See __init__() for a description of the parameters.

top_w_size(size, left, right, top, bottom)

Return the size to pass to top_w.

Graphic Widget Classes

BarGraph

class urwid.BarGraph(attlist, hatt=None, satt=None)

Create a bar graph with the passed display characteristics. see set_segment_attributes for a description of the parameters.

calculate_bar_widths(size, bardata)

Return a list of bar widths, one for each bar in data.

If self.bar_width is None this implementation will stretch the bars across the available space specified by maxcol.

calculate_display(size)

Calculate display data.

hlines_display(disp, top, hlines, maxrow)

Add hlines to display structure represented as bar_type tuple values: (bg, 0-5) bg is the segment that has the hline on it 0-5 is the hline graphic to use where 0 is a regular underscore and 1-5 are the UTF-8 horizontal scan line characters.

render(size, focus=False)

Render BarGraph.

selectable()

Return False.

set_bar_width(width)

Set a preferred bar width for calculate_bar_widths to use.

width – width of bar or None for automatic width adjustment

set_data(bardata, top, hlines=None)

Store bar data, bargraph top and horizontal line positions.

bardata – a list of bar values. top – maximum value for segments within bardata hlines – None or a bar value marking horizontal line positions

bar values are [ segment1, segment2, ... ] lists where top is the maximal value corresponding to the top of the bar graph and segment1, segment2, ... are the values for the top of each segment of this bar. Simple bar graphs will only have one segment in each bar value.

Eg: if top is 100 and there is a bar value of [ 80, 30 ] then the top of this bar will be at 80% of full height of the graph and it will have a second segment that starts at 30%.

set_segment_attributes(attlist, hatt=None, satt=None)
Parameters:
  • attlist – list containing display attribute or (display attribute, character) tuple for background, first segment, and optionally following segments. ie. len(attlist) == num segments+1 character defaults to ‘ ‘ if not specified.
  • hatt – list containing attributes for horizontal lines. First element is for lines on background, second is for lines on first segment, third is for lines on second segment etc.
  • satt

    dictionary containing attributes for smoothed transitions of bars in UTF-8 display mode. The values are in the form:

    (fg,bg) : attr

    fg and bg are integers where 0 is the graph background, 1 is the first segment, 2 is the second, ... fg > bg in all values. attr is an attribute with a foreground corresponding to fg and a background corresponding to bg.

If satt is not None and the bar graph is being displayed in a terminal using the UTF-8 encoding then the character cell that is shared between the segments specified will be smoothed with using the UTF-8 vertical eighth characters.

eg: set_segment_attributes( [‘no’, (‘unsure’,”?”), ‘yes’] ) will use the attribute ‘no’ for the background (the area from the top of the graph to the top of the bar), question marks with the attribute ‘unsure’ will be used for the topmost segment of the bar, and the attribute ‘yes’ will be used for the bottom segment of the bar.

smooth_display(disp)

smooth (col, row*8) display into (col, row) display using UTF vertical eighth characters represented as bar_type tuple values: ( fg, bg, 1-7 ) where fg is the lower segment, bg is the upper segment and 1-7 is the vertical eighth character to use.

GraphVScale

class urwid.GraphVScale(labels, top)

GraphVScale( [(label1 position, label1 markup),...], top ) label position – 0 < position < top for the y position label markup – text markup for this label top – top y position

This widget is a vertical scale for the BarGraph widget that can correspond to the BarGraph’s horizontal lines

render(size, focus=False)

Render GraphVScale.

selectable()

Return False.

set_scale([(label1 position, label1 markup), ..., ]top)

label position – 0 < position < top for the y position label markup – text markup for this label top – top y position

ProgressBar

class urwid.ProgressBar(normal, complete, current=0, done=100, satt=None)
Parameters:
  • normal – display attribute for incomplete part of progress bar
  • complete – display attribute for complete part of progress bar
  • current – current progress
  • done – progress amount at 100%
  • satt – display attribute for smoothed part of bar where the foreground of satt corresponds to the normal part and the background corresponds to the complete part. If satt is None then no smoothing will be done.
get_text()

Return the progress bar percentage text.

render(size, focus=False)

Render the progress bar.

set_completion(current)

current – current progress

BigText

class urwid.BigText(markup, font)

markup – same as Text widget markup font – instance of a Font class

get_text()

Returns (text, attributes).

urwid.get_all_fonts()

Return a list of (font name, font class) tuples.

Terminal

class urwid.Terminal(command, env=None, main_loop=None, escape_sequence=None)

A terminal emulator within a widget.

‘command’ is the command to execute inside the terminal, provided as a list of the command followed by its arguments. If ‘command’ is None, the command is the current user’s shell. You can also provide a callable instead of a command, which will be executed in the subprocess.

‘env’ can be used to pass custom environment variables. If omitted, os.environ is used.

‘main_loop’ should be provided, because the canvas state machine needs to act on input from the PTY master device. This object must have watch_file and remove_watch_file methods.

‘escape_sequence’ is the urwid key symbol which should be used to break out of the terminal widget. If it’s not specified, “ctrl a” is used.

change_focus(has_focus)

Ignore SIGINT if this widget has focus.

respond(string)

Respond to the underlying application with ‘string’.