Widget base class
See urwid.WidgetMeta definition
The default selectable() method returns this value.
A shared CommandMap instance. May be redefined in subclasses or widget instances.
Note
This method is not implemented in Widget but must be implemented by any concrete subclass
Parameters: |
|
---|---|
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.
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.
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.
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: |
|
---|---|
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).
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.
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.
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: |
|
---|---|
Returns: | True if the position was set successfully anywhere on row, False otherwise |
x.__init__(...) initializes x; see help(type(x)) for signature
Convenience function to emit signals with self as first argument.
Mark cached canvases rendered by this widget as dirty so that they will not be used again.
Read-only property that steps through decoration widgets and returns the one at the base. This default implementation returns self.
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.
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.
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.
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).
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.
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.
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'>>
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
Mixin class for widget containers implementing common container methods
x.__init__(...) initializes x; see help(type(x)) for signature
Return the .focus_position values starting from this container and proceeding along each child widget until reaching a leaf (non-container) widget.
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
a horizontally resizeable text widget
Parameters: |
|
---|
>>> 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)]
Read-only property returning the run-length encoded display attributes of this widget
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: |
|
---|
Returns: | (text, display attributes)
|
---|
>>> 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)])
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 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 ']
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 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 the text layout object, alignment and wrapping modes at the same time.
Parameters: |
|
---|
>>> t = Text(u"hi")
>>> t.set_layout('right', 'clip')
>>> t
<Text flow widget 'hi' align='right' wrap='clip'>
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 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.
Read-only property returning the complete bytes/unicode content of this widget
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: |
|
---|
>>> 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>
Read-only property returning the edit text for this widget.
Return the (x, y) coordinates of cursor within widget.
>>> Edit("? ","yes").get_cursor_coords((10,))
(5, 0)
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.
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
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 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
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 |
---|
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'
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
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
Return (x, y) coordinates for an offset into self.edit_text.
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 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 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 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 the character for masking text away.
Parameters: | mask (bytes or unicode) – hide text entered with this character, None:disable mask |
---|
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.
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.
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.
Edit widget for integer values
caption – caption markup default – default edit value
>>> IntEdit(u"", 42)
<IntEdit selectable flow widget '42' edit_pos=2>
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
Return true for decimal digits.
Return the numeric value of self.edit_text.
>>> e, size = IntEdit(), (10,)
>>> e.keypress(size, '5')
>>> e.keypress(size, '1')
>>> e.value() == 51
True
Parameters: |
|
---|
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 >']
Return label text.
>>> b = Button(u"Ok")
>>> print b.get_label()
Ok
>>> print b.label
Ok
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)
>>> connect_signal(b, 'click', handle_click)
>>> b.keypress(size, 'enter')
>>> b.keypress(size, ' ')
>>> clicked_buttons # ... = u in Python 2
[...'Cancel', ...'Cancel']
Return label text.
>>> b = Button(u"Ok")
>>> print b.get_label()
Ok
>>> print b.label
Ok
Send ‘click’ signal on button 1 press.
>>> size = (15,)
>>> b = Button(u"Ok")
>>> clicked_buttons = []
>>> def handle_click(button):
... clicked_buttons.append(button.label)
>>> 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']
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'>
Parameters: |
|
---|
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 ']
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
Return the state of the checkbox.
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
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
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
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 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)
>>> connect_signal(cb, 'change', callback_a, "user_a")
>>> 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']
Return the state of the checkbox.
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
Parameters: |
|
---|
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 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!")
>>> 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>
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)
A widget representing something in a nested tree display.
Return first child if expanded.
Handle expand & collapse requests (non-leaf nodes)
Return last child if expanded.
Return the next TreeWidget depth first from this one.
Return the previous TreeWidget depth first from this one.
Allow selection of non-leaf nodes so children may be (un)expanded
Update display widget text for parent widgets
Parameters: |
|
---|
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.
Return the position of the cursor if visible. This method is required for widgets that display a cursor.
No keys are handled by this widget. This method is required for selectable widgets.
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)
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: |
|
---|
>>> 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 wrapped widget and apply attribute. Return canvas.
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 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={}>
Parameters: |
|
---|
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|
Return the padding alignment setting.
Return the (x,y) coordinates of cursor within self._original_widget.
Return the preferred column from self._original_widget, or None.
Pass keypress to self._original_widget.
Send mouse event if position is within self._original_widget.
Set the cursor position with (x,y) coordinates of self._original_widget.
Returns True if move succeeded, False otherwise.
Return the number of columns to pad on the left and right.
Override this method to define custom padding behaviour.
Return the rows needed for self.original_widget.
Return the padding widthment setting.
Parameters: |
|
---|
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.
Return the number of rows to pad on the top and bottom.
Override this method to define custom padding behaviour.
Return cursor coords from self.original_widget if any.
Return pref_col from self.original_widget if any.
Pass keypress to self.original_widget.
Pass to self.original_widget.
Pass to self.original_widget.
Render self.original_widget with space above and/or below.
Return selectable from body.
Horizontal divider widget
Parameters: |
|
---|
>>> Divider()
<Divider flow widget>
>>> Divider(u'-')
<Divider flow widget '-'>
>>> Divider(u'x', 1, 2)
<Divider flow widget 'x' bottom=2 top=1>
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', ...' ', ...' ']
Return the number of lines that will be rendered.
>>> Divider().rows((10,))
1
>>> Divider(u'x', 1, 2).rows((10,))
4
Draw a line around original_widget.
Use ‘title’ to set an initial title text with will be centered on top of the box.
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 the Fill as a canvas and return it.
>>> SolidFill().render((4,2)).text # ... = b in Python 3
[...' ', ...' ']
>>> SolidFill('#').render((5,3)).text
[...'#####', ...'#####', ...'#####']
Subclass must override this method and have is return a widget to be used for the pop-up. This method is called once each time the pop-up is opened.
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.
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.
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: |
|
---|
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 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.
writeable property containing an indicator which part of the frame that is in focus: ‘body’, ‘header’ or ‘footer’.
Calculate the number of rows for the header and footer.
Parameters: |
|
---|---|
Returns: | (head rows, foot rows),(orig head, orig foot) orig head/foot are from rows() calls. |
Return type: | (int, int), (int, int) |
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 |
Pass keypress to widget in focus.
Pass mouse event to appropriate part of frame. Focus may be changed on button 1 press.
There are currently no options for Frame contents.
Return None as a placeholder for future options.
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’ |
---|
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 |
---|
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) |
---|
Change the current focus widget. This is used internally by methods that know the widget’s size.
See also set_focus().
Parameters: |
|
---|
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.
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
the child widget in focus or None when ListBox is empty
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.
See Widget.get_cursor_coords() for details
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.
Return (offset rows, inset rows) for focus widget.
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.
Shift the focus widget so that its cursor is visible.
Pass the event to the contained widgets. May change focus on button 1 press.
There are currently no options for ListBox contents.
Return None as a placeholder for future options.
Render ListBox and return canvas.
see Widget.render() for details
Set the focus position and try to keep the old focus in view.
Parameters: |
|
---|
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) |
---|
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: |
|
---|
Update self.pref_col from the focus widget.
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 parent directory.
Move focus to far bottom.
Move focus to very top.
Move focus to parent of widget in focus.
Handle macro-navigation keys
Widgets arranged horizontally in columns from left to right
Parameters: |
|
---|
widget_list may also contain tuples such as:
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 calcualated 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.
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.
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.
Return a list of column widths.
0 values in the list mean hide corresponding column completely
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
the child widget in focus or None when Columns is empty
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.
index of child widget in focus. Raises IndexError if read when Columns is empty, or when set to an invalid index.
Return the cursor coordinates from the focus widget.
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.
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.
Return the pref col from the column in focus.
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. |
---|
Send event to appropriate column. May change focus on button 1 press.
Choose a selectable column to focus based on the coords.
see Widget.move_cursor_coords() for details
Return a new options tuple for use in a Pile’s .contents list.
This sets an entry’s width type: one of the following:
Parameters: |
|
---|
Render columns and return canvas.
Parameters: |
|
---|
Return the number of rows required by the columns. This only makes sense if widget_list contains flow widgets.
see Widget.rows() for details
Return the selectable value of the focus column.
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 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.
A pile of widgets stacked vertically from top to bottom
Parameters: |
|
---|
widget_list may also contain tuples such as:
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.
The contents of this Pile as a list of (widget, options) tuples.
options currently may be one of
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
the child widget in focus or None when Pile is empty
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.
index of child widget in focus. Raises IndexError if read when Pile is empty, or when set to an invalid index.
Return the cursor coordinates of the focus widget.
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.
Return a list of the number of rows used by each widget in self.contents
Return a size appropriate for passing to self.contents[i][0].render
Return the preferred column for the cursor, or None.
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.
Pass the keypress to the widget in focus. Unhandled ‘up’ and ‘down’ keys may cause a focus change.
Pass the event to the contained widget. May change focus on button 1 press.
Capture pref col and set new focus.
Return a new options tuple for use in a Pile’s contents list.
Parameters: |
|
---|
Return True if the focus item is selectable.
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 |
---|
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: |
|
---|
The width of each cell in the GridFlow. Setting this value affects all 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.
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.
the child widget in focus or None when GridFlow is empty
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.
index of child widget in focus. Raises IndexError if read when GridFlow is empty, or when set to an invalid index.
Actually generate display widget (ignoring cache)
Get cursor from display widget.
Arrange the cells into columns (and possibly a pile) for display, input or to calculate rows, and update the display widget.
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.
Return pref col from display widget.
Pass keypress to display widget for handling. Captures focus changes.
Set the widget in focus based on the col + row.
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 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 |
---|
Adapter for using a box widget where a flow widget would usually go
Create a flow widget that contains a box widget
Parameters: |
|
---|
>>> BoxAdapter(SolidFill(u"x"), 5) # 5-rows of x's
<BoxAdapter flow widget <SolidFill box widget 'x'> height=5>
Return the predetermined height (behave like a flow widget)
>>> BoxAdapter(SolidFill(u"x"), 5).rows((20,))
5
Overlay contains two box widgets and renders one on top of the other
Parameters: |
|
---|
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.
Return (padding left, right, filler top, bottom).
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.
the top widget in this overlay is always in focus
index of child widget in focus, currently always 1
Return cursor coords from top_w, if any.
Pass keypress to top_w.
Pass event to top_w, ignore if outside of top_w.
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 top_w overlayed on bottom_w.
Return selectable from top_w.
Adjust the overlay size and position parameters.
See __init__() for a description of the parameters.
Return the size to pass to top_w.
Create a bar graph with the passed display characteristics. see set_segment_attributes for a description of the parameters.
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 data.
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 BarGraph.
Return False.
Set a preferred bar width for calculate_bar_widths to use.
width – width of bar or None for automatic width adjustment
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%.
Parameters: |
|
---|
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 (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( [(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 GraphVScale.
Return False.
label position – 0 < position < top for the y position label markup – text markup for this label top – top y position
Parameters: |
|
---|
Return the progress bar percentage text.
Render the progress bar.
current – current progress
markup – same as Text widget markup font – instance of a Font class
Returns (text, attributes).
Return a list of (font name, font class) tuples.
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.
Ignore SIGINT if this widget has focus.
Respond to the underlying application with ‘string’.