# Urwid %version% Tutorial

Urwid Home Page / Example Screenshots / UTF-8 Screenshots / Tutorial / Reference

%toc_left% | %toc_right%

The programs in this tutorial are available in your Urwid distribution. Run the command "./docgen_tutorial.py -s" to output the example scripts.

{contents}

# Urwid Tutorial Template File

This file is used by docgen_tutorial.py to generate the tutorial documentation tutorial.html.

Items in the list that follows are parsed by docgen_tutorial.py. Each item has a tag and a name, separated by a comma. Whitespace on either side of the comma is stripped.

Items without tags are new sections.

A --- separates the left and right columns in the table of contents.

    Tag, Section or Item Name
    {section_data}
    ,            Hello World Example
    min,         Minimal Urwid Application
    input,       Handling Input
    attr,        AttrMap Widgets and Text Attributes
    highcolors,  High Color Modes
    ,            Conversation Example
    edit,        Edit Widgets
    frlb,        Events and ListBox Widgets
    lbcont,      Modifying ListBox Content
    ,            Zen of ListBox
    lbscr,       ListBox Focus and Scrolling
    lbdyn,       Dynamic ListBox with List Walker
    lbfocus,     Setting the Focus
    ---
    ,            Combining Widgets
    pile,        Piling Widgets
    cols,        Dividing into Columns
    grid,        GridFlow Arrangement
    overlay,     Overlay Widgets
    ,            Creating Custom Widgets
    wmod,        Modifying Existing Widgets
    wanat,       Anatomy of a Widget
    wsel,        Creating Selectable Widgets
    wcur,        Widgets Displaying the Cursor
    {/section_data}

{toc_section}

%snum%. %name%
{/toc_section}

{toc_item}

%snum%.%inum%. %name%
{/toc_item}

{section_head}

## %snum%. %name%

{/section_head}

{section_body}

### %snum%.%inum%. %name% [back to top]

%content%
{/section_body}

{body[min]} This program displays the string "Hello World" in the top left corner of the screen and will run until interrupted with CTRL+C (^C).

    %example[0]%

- The Text widget handles formatting blocks of text, wrapping to the next line when necessary. Widgets like this are called "flow widgets" because their sizing can have a number of columns given, in this case the full screen width, then they will flow to fill as many rows as necessary.
- The Filler is widget fills in blank lines above or below flow widgets so that they can be displayed in a fixed number of rows. This Filler will align our Text to the top of the screen, filling all the rows below with blank lines. Widgets which are given both the number of columns and number of rows they must be displayed in are called "box widgets". The "topmost" widget displayed on the screen must be a box widget.
- The MainLoop class handles displaying our widgets as well as input from the user. In this case our widgets can't handle the input so we need to interrupt the program to exit with ^C.

%result[0]%
{/body[min]}

{body[input]} This program initially displays the string "Hello World", then it displays each key pressed, exiting when the user presses Q.

    %example[0]%

- The MainLoop class has an optional function parameter unhandled_input This function will be called once for each keypress that is not handled by the widgets being displayed.
- None of the widgets being displayed here handle input, so every key the user presses will be passed to the show_or_exit function.
- The ExitMainLoop exception is used to exit cleanly from the MainLoop.run() function when the user presses Q. All other input is displayed by replacing the current Text widget's content.

%result[0]%
%result[1]%
%result[2]%
%result[3]%
%result[4]%
{/body[input]}

{body[attr]} This program displays the string "Hello World" in the center of the screen. It uses different attributes for the text, the space on either side of the text and the space above and below the text. It waits for a keypress before exiting.

    %example[0]%

- Attributes are defined as part of a palette. Valid foreground, background and setting values are documented in the AttrSpec class. A palette is a list of tuples containing:
  1. Name of the attribute, typically a string
  2. Foreground color and settings for 16-color (normal) mode
  3. Background color for normal mode
  4. Settings for monochrome mode (optional)
  5. Foreground color and settings for 88 and 256-color modes (optional, see next example)
  6. Background color for 88 and 256-color modes (optional)
- The palette is passed to MainLoop to make it available to our program
- A Text widget is created containing the string " Hello World " with attribute "banner". The attributes of text in a Text widget is set by using a (attribute, text) tuple instead of a simple text string. Text attributes will flow with the text, and multiple attributes may be specified by combining tuples into a list.
- An AttrMap widget is created to wrap the text widget with attribute "streak". AttrMap widgets allow you to map any attribute to any other attribute, but by default they will set the attribute of everything that does not already have an attribute. In this case the text has an attribute, so only the areas around the text used for alignment will be have the new attribute.
- A second AttrMap widget is created to wrap the filler widget with attribute "bg".

When this program is run you can now clearly see the separation of the text, the alignment around the text, and the filler above and below the text. This is how these widgets react to being resized:
%result[0]%
%result[1]%
%result[2]%
%result[3]%
{/body[attr]}

{body[highcolors]} This program displays the string "Hello World" in the center of the screen. It uses a number of 256-color-mode background attributes to decorate the text, and will work in any terminal that supports 256-color mode. It will exit when Q is pressed.

    %example[0]%

- This palette only defines values for the high color foreground and backgrounds, because only the high colors will be used. A real application should define values for all the modes in their palette. Valid foreground, background and setting values are documented in the AttrSpec class.
- Divider widgets are used to create blank lines, colored with AttrMap.
- A Pile widget arranges the Divider widgets above and below our text.
- Behind the scenes our MainLoop class has created a raw_display.Screen object for drawing the screen. The program is put into 256-color mode by using the screen object's set_terminal_properties method. This method works only when using the default raw_display Screen class in our MainLoop.

%result[0]%
{/body[highcolors]}

{body[edit]} This program asks for your name then responds "Nice to meet you, (your name)."

    %example[0]%

- An Edit widget is created with the caption "What is your name?". A newline at the end of the caption makes the user input start on the next row.
- Most keystrokes will be handled by the Edit widget, allowing the user to enter their name.
- The unhandled_input function will replace the Edit widget inside the Filler widget with a reply when the user presses ENTER.
- When the user presses ENTER again the unhandled_input function will cause the program to exit.

The Edit widget has many capabilities. It lets you make corrections and move the cursor around with the HOME, END and arrow keys. It is based on the Text widget so it supports the same wrapping and alignment modes.
%result[0]%
%result[1]%
%result[2]%
{/body[edit]}

{body[frlb]} This program asks for your name and responds "Nice to meet you, (your name)" while you type your name. ENTER exits.

    %example[0]%

- An Edit widget and Text reply widget are created, like in the previous example.
- A SimpleListWalker is then created to manage the contents and focus of our ListBox. The SimpleListWalker behaves just like a list of widgets, and can be modified like a regular list.
- A ListBox is created and passed the SimpleListWalker. The ListBox is a box widget and allows scrolling through its contents. This example is simple enough that we could have used a Pile widget and Filler widget instead, but we will see how the ListBox can be useful in later examples.
- The connect_signal function is used to attach our on_ask_change function to our Edit widget's "change" event. Now any time the content of the Edit widget changes on_ask_change will be called and passed the new content.
- Now on_ask_change updates the reply text as the user enters their name.

%result[0]%
%result[1]%
%result[2]%
%result[3]%
{/body[frlb]}

{body[lbcont]} This program asks for your name and responds "Nice to meet you, (your name)." It then asks again, and again. Old values may be changed and the responses will be updated when you press ENTER. ENTER on a blank line exits.

    %example[0]%

- When the user presses ENTER:
  - The widget in focus and its current position is retrieved by calling the get_focus function.
  - If the widget in focus does not have an edit_text attribute, then it is not one of the Edit widgets we are interested in. One of the Text widgets might receive focus if it covers the entire visible area of the ListBox widget and there is no Edit widget to take focus. While this is unlikely, it should be handled or the program will fail when trying to access it.
  - If there is no edit text we exit the program.
  - The widget after the widget in focus (if any exists) is replaced with a response.
  - If there is no widget after that widget, a new Edit widget is created.
  - The focus is then moved to the next Edit widget by calling set_focus.
- All other keys are passed to the top widget to handle. The ListBox widget does most of the hard work:
  - UP and DOWN will change the focus and/or scroll the widgets in the list box.
  - PAGE UP and PAGE DOWN will try to move the focus one screen up or down.
  - The cursor's column is maintained as best as possible when moving from one Edit widget to another.

%result[0]%
%result[1]%
%result[2]%
{/body[lbcont]}

{body[lbscr]} The ListBox is a box widget that contains flow widgets. Its contents are displayed stacked vertically, and the ListBox allows the user to scroll through its content. One of the flow widgets displayed in the ListBox is the focus widget. The ListBox passes key presses to the focus widget to allow the user to interact with it. If the focus widget does not handle a keypress then the ListBox may handle the keypress by scrolling and/or selecting another widget to become the focus widget.
The ListBox tries to do the most sensible thing when scrolling and changing focus. When the widgets displayed are all Text widgets or other unselectable widgets then the ListBox will behave like a web browser does when the user presses UP, DOWN, PAGE UP and PAGE DOWN: new text is immediately scrolled in from the top or bottom. The ListBox chooses one of the visible widgets as its focus widget when scrolling. When scrolling up the ListBox chooses the topmost widget as the focus, and when scrolling down the ListBox chooses the bottommost widget as the focus.
When all the widgets displayed are not selectable the user would typically have no way to tell which widget is in focus, but if we wrap the widgets with AttrWrap we can see what is happening while the focus changes:

    %example[0]%

%result[0]%
%result[1]%
%result[2]%
%result[3]%
%result[4]%
%result[5]%
The ListBox remembers the location of the widget in focus as either an "offset" or an "inset". An offset is the number of rows between the top of the ListBox and the beginning of the focus widget. An offset of zero corresponds to a widget with its top aligned with the top of the ListBox. An inset is the fraction of rows of the focus widget that are "above" the top of the ListBox and not visible. The ListBox uses this method of remembering the focus widget location so that when the ListBox is resized the text displayed will stay roughly aligned with the top of the ListBox.
%result[6]%
%result[7]%
%result[8]%
When there are selectable widgets in the ListBox the focus will move between the selectable widgets, skipping the unselectable widgets. The ListBox will try to scroll all the rows of a selectable widget into view so that the user can see the new focus widget in its entirety. This behavior can be used to bring more than a single widget into view by using composite widgets to combine a selectable widget with other widgets that should be displayed at the same time. {/body[lbscr]}

{body[lbdyn]} While the ListBox stores the location of its focus widget, it does not directly store the actual focus widget or other contents of the ListBox. The storage of a ListBox's content is delegated to a "List Walker" object. If a list of widgets is passed to the ListBox constructor then it creates a SimpleListWalker object to manage the list.
When the ListBox is rendering a canvas or handling input it will:

1. Call the get_focus method of its list walker object. This method will return the focus widget and a position object.
2. Optionally call the get_prev method of its List Walker object one or more times, initially passing the focus position and then passing the new position returned on each successive call. This method will return the widget and position object "above" the position passed.
3. Optionally call the get_next method of its List Walker object one or more times, similarly, to collect widgets and position objects "below" the focus position.
4. Optionally call the set_focus method passing one of the position objects returned in the previous steps.

This is the only way the ListBox accesses its contents, and it will not store copies of any of the widgets or position objects beyond the current rendering or input handling operation.
The SimpleListWalker stores a list of widgets, and uses integer indexes into this list as its position objects. It stores the focus position as an integer, so if you insert a widget into the list above the focus position then you need to remember to increment the focus position in the SimpleListWalker object or the contents of the ListBox will shift.
A custom List Walker object may be passed to the ListBox constructor instead of a plain list of widgets. List Walker objects must implement the List Walker interface.
The fib.py example program demonstrates a custom list walker that doesn't store any widgets. It uses a tuple of two successive Fibonacci numbers as its position objects and it generates Text widgets to display the numbers on the fly. The result is a ListBox that can scroll through an unending list of widgets.
The edit.py example program demonstrates a custom list walker that loads lines from a text file only as the user scrolls them into view. This allows even huge files to be opened almost instantly.
The browse.py example program demonstrates a custom list walker that uses a tuple of strings as position objects, one for the parent directory and one for the file selected. The widgets are cached in a separate class that is accessed using a dictionary indexed by parent directory names. This allows the directories to be read only as required. The custom list walker also allows directories to be hidden from view when they are "collapsed". {/body[lbdyn]}

{body[lbfocus]} The easiest way to change the current ListBox focus is to call the set_focus method. This method doesn't require that you know the ListBox's current dimensions (maxcol, maxrow). It will wait until the next call to either keypress or render to complete setting the offset and inset values using the dimensions passed to that method.
The position object passed to set_focus must be compatible with the List Walker object that the ListBox is using. For SimpleListWalker the position is the integer index of the widget within the list.
The coming_from parameter should be set if you know that the old position is "above" or "below" the previous position. When the ListBox completes setting the offset and inset values it tries to find the old widget among the visible widgets. If the old widget is still visible, if will try to avoid causing the ListBox contents to scroll up or down from its previous position. If the widget is not visible, then the ListBox will:

- Display the new focus at the bottom of the ListBox if coming_from is "above".
- Display the new focus at the top of the ListBox if coming_from is "below".
- Display the new focus in the middle of the ListBox if coming_from is None.

If you know exactly where you want to display the new focus widget within the ListBox you may call set_focus_valign. This method lets you specify the "top", "bottom", "middle", a relative position or the exact number of rows from the top or bottom of the ListBox. {/body[lbfocus]}

{body[pile]} Pile widgets are used to combine multiple widgets by stacking them vertically. A Pile can manage selectable widgets by keeping track of which widget is in focus and it can handle moving the focus between widgets when the user presses the UP and DOWN keys. A Pile will also work well when used within a ListBox.
A Pile is selectable only if its focus widget is selectable. If you create a Pile containing one Text widget and one Edit widget the Pile will choose the Edit widget as its default focus widget. To change the pile's focus widget you can call set_focus. {/body[pile]}

{body[cols]} Columns widgets may be used to arrange either flow widgets or box widgets horizontally into columns. Columns widgets will manage selectable widgets by keeping track of which column is in focus and it can handle moving the focus between columns when the user presses the LEFT and RIGHT keys. Columns widgets also work well when used within a ListBox.
Columns widgets are selectable only if the column in focus is selectable. If a focus column is not specified the first selectable widget will be chosen as the focus column. The set_focus method may be used to select the focus column. {/body[cols]}

{body[grid]} The GridFlow widget is a flow widget designed for use with Button, CheckBox and RadioButton widgets. It renders all the widgets it contains the same width and it arranges them from left to right and top to bottom.
The GridFlow widget uses Pile, Columns, Padding and Divider widgets to build a display widget that will handle the keyboard input and rendering. When the GridFlow widget is resized it regenerates the display widget to accommodate the new space. {/body[grid]}

{body[overlay]} The Overlay widget is a box widget that contains two other box widgets. The bottom widget is rendered the full size of the Overlay widget and the top widget is placed on top, obscuring an area of the bottom widget. This widget can be used to create effects such as overlapping "windows" or pop-up menus.
The Overlay widget always treats the top widget as the one in focus. All keyboard input will be passed to the top widget.
If you want to use a flow flow widget for the top widget, first wrap the flow widget with a Filler widget. {/body[overlay]}

{body[wmod]} The easiest way to create a custom widget is to modify an existing widget. This can be done by either subclassing the original widget or by wrapping it. Subclassing is appropriate when you need to interact at a very low level with the original widget, such as if you are creating a custom edit widget with different behavior than the usual Edit widgets. If you are creating a custom widget that doesn't need tight coupling with the original widget, such as a widget that displays customer address information, then wrapping is more appropriate.
The WidgetWrap class simplifies wrapping existing widgets. You can create a custom widget simply by creating a subclass of WidgetWrap and passing a widget into WidgetWrap's constructor.
This is an example of a custom widget that uses WidgetWrap:

    %example[0]%

The above code creates a group of RadioButtons and provides a method to query the state of the buttons.
Wrapped widgets may also override the standard widget methods. These methods are described in following sections. {/body[wmod]}

{body[wanat]} Any object that follows the Widget interface definition may be used as a widget. Box widgets must implement selectable and render methods, and flow widgets must implement selectable, render and rows methods.

    %example[0]%

The above code implements two widget classes. Pudding is a flow widget and BoxPudding is a box widget. Pudding will render as much "Pudding" as will fit in a single row, and BoxPudding will render as much "Pudding" as will fit into the entire area given.
It is not strictly necessary to inherit from BoxWidget or FlowWidget, but doing so does add some documentation to your code.
Note that the rows and render methods' focus parameter must have a default value of False. Also note that for flow widgets the number of rows returned by the rows method must match the number of rows rendered by the render method.
In most cases it is easier to let other widgets handle the rendering and row calculations for you:

    %example[1]%

The NewPudding class behaves the same way as the Pudding class above, but in NewPudding you can change the way the widget appears by modifying only the display_widget method, whereas in the Pudding class you may have to modify both the render and rows methods.
To improve the efficiency of your Urwid application you should be careful of how long your rows methods take to execute. The rows methods may be called many times as part of input handling and rendering operations. If you are using a display widget that is time consuming to create you should consider caching it to reduce its impact on performance.
It is possible to create a widget that will behave as either a flow widget or box widget depending on what is required:

    %example[2]%

MultiPudding will work in place of either Pudding or BoxPudding above. The number of elements in the size tuple determines whether the containing widget is expecting a flow widget or a box widget. {/body[wanat]}

{body[wsel]} Selectable widgets such as Edit and Button widgets allow the user to interact with the application. A widget is selectable if its selectable method returns True. Selectable widgets must implement the keypress method to handle keyboard input.

    %example[0]%

The SelectablePudding widget will display its contents in uppercase when it is in focus, and it allows the user to "eat" the pudding by pressing each of the letters P, U, D, D, I, N and G on the keyboard. When the user has "eaten" all the pudding the widget will reset to its initial state.
Note that keys that are unhandled in the keypress method are returned so that another widget may be able to handle them. This is a good convention to follow unless you have a very good reason not to. In this case the UP and DOWN keys are returned so that if this widget is in a ListBox the ListBox will behave as the user expects and change the focus or scroll the ListBox. {/body[wsel]}

{body[wcur]} Widgets that display the cursor must implement the get_cursor_coords method. Similar to the rows method for flow widgets, this method lets other widgets make layout decisions without rendering the entire widget. The ListBox widget in particular uses get_cursor_coords to make sure that the cursor is visible within its focus widget.

    %example[0]%

CursorPudding will let the user move the cursor through the widget by pressing LEFT and RIGHT. The cursor must only be added to the canvas when the widget is in focus. The get_cursor_coords method must always return the same cursor coordinates that render does.
A widget displaying a cursor may choose to implement get_pref_col. This method returns the preferred column for the cursor, and is called when the focus is moving up or down off this widget.
Another optional method is move_cursor_to_coords. This method allows other widgets to try to position the cursor within this widget. The ListBox widget uses move_cursor_to_coords when changing focus and when the user pressed PAGE UP or PAGE DOWN. This method must return True on success and False on failure. If the cursor may be placed at any position within the row specified (not only at the exact column specified) then this method must move the cursor to that position and return True.

    %example[1]%

{/body[wcur]}

{/contents}