<html> <head> <title>Urwid 0.9.8.4 Tutorial</title> <style type="text/css"> h1 { text-align: center; } h2 { margin: 40px 0 0 0; padding: 10px; background: #6d96e8;} h3 { margin: 0 0 3px 0; padding: 12px 6px 6px 6px; background: #efef96;} .code { background: #dddddd; padding: 5px; margin: 7px 20px; } .l1 { margin: 12px 0 0 0; } .l2 { margin-left: 20px; } .shot { padding: 5px 20px 5px 0px; float: left; } .back { font-size:small; padding-left: 20px; } </style> <body> <a name="top"></a> <h1>Urwid 0.9.8.4 Tutorial</h1> <div style="text-align: center;"> <a href="http://excess.org/urwid/">Urwid Home Page</a> / <a href="http://excess.org/urwid/examples.html">Example Screenshots</a> / <a href="http://excess.org/urwid/utf8examples.html">UTF-8 Screenshots</a> / Tutorial / <a href="reference.html">Reference</a> </div> <br> <table width="100%"><tr><td width="50%" valign="top"> <div class="l1">1. Hello World Example</div> <div class="l2"><a href="#min">1.1. Minimal Urwid Application</a></div> <div class="l2"><a href="#text">1.2. Text and Filler Widgets</a></div> <div class="l2"><a href="#attr">1.3. AttrWrap Widgets and Text Attributes</a></div> <div class="l2"><a href="#resize">1.4. Live Resizing</a></div> <div class="l1">2. Conversation Example</div> <div class="l2"><a href="#edit">2.1. Edit Widgets</a></div> <div class="l2"><a href="#frlb">2.2. Frame and ListBox Widgets</a></div> <div class="l2"><a href="#lbcont">2.3. Modifying ListBox Content</a></div> <div class="l1">3. Zen of ListBox</div> <div class="l2"><a href="#lbscr">3.1. ListBox Focus and Scrolling</a></div> <div class="l2"><a href="#lbdyn">3.2. Dynamic ListBox with List Walker</a></div> <div class="l2"><a href="#lbfocus">3.3. Setting the Focus</a></div> </td><td width="50%" valign="top"> <div class="l1">4. Combining Widgets</div> <div class="l2"><a href="#pile">4.1. Piling Widgets</a></div> <div class="l2"><a href="#cols">4.2. Dividing into Columns</a></div> <div class="l2"><a href="#grid">4.3. GridFlow Arrangement</a></div> <div class="l2"><a href="#overlay">4.4. Overlay Widgets</a></div> <div class="l1">5. Creating Custom Widgets</div> <div class="l2"><a href="#wmod">5.1. Modifying Existing Widgets</a></div> <div class="l2"><a href="#wanat">5.2. Anatomy of a Widget</a></div> <div class="l2"><a href="#wsel">5.3. Creating Selectable Widgets</a></div> <div class="l2"><a href="#wcur">5.4. Widgets Displaying the Cursor</a></div> </td></tr></table> <h2>1. Hello World Example</h2> <h3><a name="min">1.1. Minimal Urwid Application</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> This program displays the string "Hello World" in the top left corner of the screen and waits for a keypress before exiting. <pre class="code">import urwid.curses_display import urwid ui = urwid.curses_display.Screen() def run(): canvas = urwid.TextCanvas(["Hello World"]) ui.draw_screen( (20, 1), canvas ) while not ui.get_input(): pass ui.run_wrapper( run )</pre> <ul> <li>The <a href="reference.html#curses_display.Screen">curses_display.Screen</a> class provides access to the curses library. Its member function <a href="reference.html#Screen-run_wrapper">run_wrapper</a> initializes curses full-screen mode and then calls the "run" function passed. It will also take care of restoring the screen when the "run" function exits. <li>A <a href="reference.html#TextCanvas">TextCanvas</a> is created containing one row with the string "Hello World". <li>The canvas is passed to the <a href="reference.html#Screen-draw_screen">draw_screen</a> function along with a fixed screen size of 20 columns and 1 row. If the terminal window this program is run from is larger than 20 by 1 the text will appear in the top left corner. <li>The <a href="reference.html#Screen-get_input">get_input</a> function is then called until it returns something. It must be called in a loop because by default it will time out after one second and return an empty list when there is no input. </ul> Creating canvases directly in this way is generally only done when writing custom widget classes. Note that the draw_screen function must be passed a canvas and a screen size that matches it, for backwards compatibility. <div align="center"><pre><span style="color:black;background:silver">Hello World</span> </pre></div> <br clear="left"> <br> <h3><a name="text">1.2. Text and Filler Widgets</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> This program displays the string "Hello World" in the center of the screen and waits for a keypress before exiting. <pre class="code">import urwid.curses_display import urwid ui = urwid.curses_display.Screen() def run(): cols, rows = ui.get_cols_rows() txt = urwid.Text("Hello World", align="center") fill = urwid.Filler( txt ) canvas = fill.render( (cols, rows) ) ui.draw_screen( (cols, rows), canvas ) while not ui.get_input(): pass ui.run_wrapper( run )</pre> <ul> <li><a href="reference.html#Screen-get_cols_rows">get_cols_rows</a> is used to get the dimensions from the terminal and store them as "cols" and "rows". <li>A <a href="reference.html#Text">Text</a> widget is created containing the string "Hello World". It is set to display with "center" alignment. Text widgets are a kind of <a href="reference.html#FlowWidget">FlowWidget</a>. Flow widgets can fill one or more rows, depending on their content and the number of columns available. Text widgets use more than one row when they contain newline characters or when the text must be split across rows. <li>A <a href="reference.html#Filler">Filler</a> widget is created to wrap the text widget. Filler widgets are a kind of <a href="reference.html#BoxWidget">BoxWidget</a>. Box widgets have a fixed number of columns and rows displayed. This widget will pad the "Hello World" text widget until it fills the required number of rows. <li>A canvas is created by calling the <a href="reference.html#Filler-render">render</a> function on the topmost widget. The filler render function will call the render function of the "Hello World" text widget and combine its canvas with padding rows to fill the terminal window. </ul> Flow widgets and box widgets are not interchangeable. The first parameter of the render function of a box widget is a two-element tuple (columns, rows) and the first parameter of the render function of a flow widget is a one-element tuple (columns, ). This difference makes sure that when the wrong type of widget is used, such as a box widget inside a filler widget, a ValueError exception will be thrown. <div align="center"><pre><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> Hello World </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> </pre></div> <br clear="left"> <br> <h3><a name="attr">1.3. AttrWrap Widgets and Text Attributes</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> 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. <pre class="code">import urwid.curses_display import urwid ui = urwid.curses_display.Screen() ui.register_palette( [ ('banner', 'black', 'light gray', ('standout', 'underline')), ('streak', 'black', 'dark red', 'standout'), ('bg', 'black', 'dark blue'), ] ) def run(): cols, rows = ui.get_cols_rows() txt = urwid.Text(('banner', " Hello World "), align="center") wrap1 = urwid.AttrWrap( txt, 'streak' ) fill = urwid.Filler( wrap1 ) wrap2 = urwid.AttrWrap( fill, 'bg' ) canvas = wrap2.render( (cols, rows) ) ui.draw_screen( (cols, rows), canvas ) while not ui.get_input(): pass ui.run_wrapper( run )</pre> <ul> <li>After creating the <a href="reference.html#curses_display.Screen">curses_display.Screen</a> object and before calling <a href="reference.html#Screen-run_wrapper">run_wrapper</a>, <a href="reference.html#Screen-register_palette">register_palette</a> is called to set up some attributes: <ul> <li>"banner" is black text on a light gray background, or reversed attributes and underlined in monochrome mode <li>"streak" is black text on a dark red background, or reversed attributes in monochrome mode <li>"bg" is black text on a dark blue background, or normal in monochrome mode </ul> <li>A <a href="reference.html#Text">Text</a> 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. <li>An <a href="reference.html#AttrWrap">AttrWrap</a> widget is created to wrap the text widget with attribute "streak". AttrWrap widgets will set the attribute of everything that they wrap that does not already have an attribute set. In this case the text has an attribute, so only the areas around the text used for alignment will be have the new attribute. <li>A <a href="reference.html#Filler">Filler</a> widget is created to wrap the AttrWrap widget and fill the rows above and below it. <li>A second <a href="reference.html#AttrWrap">AttrWrap</a> widget is created to wrap the filler widget with attribute "bg". <li>A canvas is created by calling the <a href="reference.html#AttrWrap-render">render</a> function on the topmost widget. </ul> AttrWrap widgets will behave like flow widgets or box widgets depending on how they are called. The filler widget treats the first AttrWrap widget as a flow widget when calling its render function, so the AttrWrap widget calls the text widget's render function the same way. The second AttrWrap is used as the topmost widget and treated as a box widget, so it calls the filler render function in the same way. <div align="center"><pre><span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#c00000"> </span><span style="color:black;background:silver"> Hello World </span><span style="color:black;background:#c00000"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> </pre></div> <br clear="left"> <br> <h3><a name="resize">1.4. Live Resizing</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> 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. When the window is resized it will repaint the screen, and it will exit when Q is pressed. <pre class="code">import urwid.curses_display import urwid ui = urwid.curses_display.Screen() ui.register_palette( [ ('banner', 'black', 'light gray', ('standout', 'underline')), ('streak', 'black', 'dark red', 'standout'), ('bg', 'black', 'dark blue'), ] ) def run(): cols, rows = ui.get_cols_rows() txt = urwid.Text(('banner', " Hello World "), align="center") wrap1 = urwid.AttrWrap( txt, 'streak' ) fill = urwid.Filler( wrap1 ) wrap2 = urwid.AttrWrap( fill, 'bg' ) while True: canvas = wrap2.render( (cols, rows) ) ui.draw_screen( (cols, rows), canvas ) keys = ui.get_input() if "q" in keys or "Q" in keys: break if "window resize" in keys: cols, rows = ui.get_cols_rows() ui.run_wrapper( run )</pre> The <a href="reference.html#Screen-get_input">get_input</a> function will return "window resize" among keys pressed when the window is resized. It is a good idea to check for uppercase and lowercase letters on input to avoid confusing users. <div class="shot"><pre><span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#c00000"> </span><span style="color:black;background:silver"> Hello World </span><span style="color:black;background:#c00000"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> </pre></div> <div class="shot"><pre><span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#c00000"> </span><span style="color:black;background:silver"> Hello</span><span style="color:black;background:#c00000"> </span> <span style="color:black;background:#c00000"> </span><span style="color:black;background:silver">World </span><span style="color:black;background:#c00000"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#0000c0"> </span> </pre></div> <div class="shot"><pre><span style="color:black;background:#0000c0"> </span> <span style="color:black;background:#c00000"> </span><span style="color:black;background:silver"> Hello World </span><span style="color:black;background:#c00000"> </span> <span style="color:black;background:#0000c0"> </span> </pre></div> <div class="shot"><pre><span style="color:black;background:#c00000"> </span><span style="color:black;background:silver"> Hello World </span><span style="color:black;background:#c00000"> </span> <span style="color:black;background:#0000c0"> </span> </pre></div> <br clear="left"> <br> <h2>2. Conversation Example</h2> <h3><a name="edit">2.1. Edit Widgets</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> This program asks for your name then responds "Nice to meet you, (your name)." <pre class="code">import urwid.curses_display import urwid ui = urwid.curses_display.Screen() def run(): cols, rows = ui.get_cols_rows() ask = urwid.Edit("What is your name?\n") fill = urwid.Filler( ask ) reply = None while True: canvas = fill.render( (cols, rows), focus=True ) ui.draw_screen( (cols, rows), canvas ) keys = ui.get_input() for k in keys: if k == "window resize": cols, rows = ui.get_cols_rows() continue if reply is not None: return if k == "enter": reply = urwid.Text( "Nice to meet you,\n"+ ask.edit_text+"." ) fill.body = reply if fill.selectable(): fill.keypress( (cols, rows), k ) ui.run_wrapper( run )</pre> <ul> <li>An <a href="reference.html#Edit">Edit</a> 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. <li>A <a href="reference.html#Filler">Filler</a> widget is created to wrap the edit widget. Its <a href="reference.html#Filler-render">render</a> function is called to create the canvas. The render function is called with the optional parameter "focus" set to True. This parameter allows the wrapped Edit widget to render its cursor. <li>Keys are processed one at a time. Most keys are sent to the Filler widget's <a href="reference.html#Filler-keypress">keypress</a> function which will call the Edit widget's <a href="reference.html#Edit-keypress">keypress</a> function to handle the key. <li>Once the ENTER key is pressed the wrapped object in the Filler widget is changed to a reply text. <li>Any keypress then causes the program to exit. </ul> 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. <div class="shot"><pre><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver">What is your name? </span> <span style="color:silver;background:black"> </span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> </pre></div> <div class="shot"><pre><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver">What is your name? </span> <span style="color:black;background:silver">Arthur, King of the </span> <span style="color:black;background:silver">Britons</span><span style="color:silver;background:black"> </span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> </pre></div> <div class="shot"><pre><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Nice to meet you, </span> <span style="color:black;background:silver">Arthur, King of the </span> <span style="color:black;background:silver">Britons. </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> </pre></div> <br clear="left"> <br> <h3><a name="frlb">2.2. Frame and ListBox Widgets</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> This program asks for your name and responds "Nice to meet you, (your name)" <i>while</i> you type your name. F8 exits. <pre class="code">import urwid.curses_display import urwid class Conversation(object): def __init__(self): self.items = urwid.SimpleListWalker( [self.new_question()]) self.listbox = urwid.ListBox(self.items) instruct = urwid.Text("Press F8 to exit.") header = urwid.AttrWrap( instruct, 'header' ) self.top = urwid.Frame(self.listbox, header) def main(self): self.ui = urwid.curses_display.Screen() self.ui.register_palette([ ('header', 'black', 'dark cyan', 'standout'), ('I say', 'default', 'default', 'bold'), ]) self.ui.run_wrapper( self.run ) def run(self): size = self.ui.get_cols_rows() while True: self.draw_screen( size ) keys = self.ui.get_input() if "f8" in keys: break for k in keys: if k == "window resize": size = self.ui.get_cols_rows() continue self.top.keypress( size, k ) if keys: name = self.items[0].edit_text self.items[1:2] = [self.new_answer(name)] def draw_screen(self, size): canvas = self.top.render( size, focus=True ) self.ui.draw_screen( size, canvas ) def new_question(self): return urwid.Edit(('I say',"What is your name?\n")) def new_answer(self, name): return urwid.Text(('I say',"Nice to meet you, "+name+"\n")) Conversation().main()</pre> <ul> <li>In the __init__ function a list called self.items is created. It contains an Edit widget with the caption "What is your name?". <li>A <a href="reference.html#ListBox">ListBox</a> widget called self.listbox is created that is passed the self.items list. This ListBox widget will display and scroll through the widgets in that list. ListBox widgets default to using the first item in the list as the focus. <li>A <a href="reference.html#Frame">Frame</a> widget called self.top is created that contains self.listbox and some header text. Frame widgets wrap around a box widget and may have header and footer flow widgets. The header and footer are always displayed. The contained box widget uses the remaining space in between. <li>When a key is pressed the reply text is inserted or updated in self.items. This updated text will be displayed by self.listbox. </ul> When changing the contents of ListBox widgets remember to use in-place editing operations on the list, eg. "list = list + [something]" will not work, use "list += [something]" instead. The former code will create a new list but the ListBox will still be displaying the old list. <div class="shot"><pre><span style="color:black;background:teal">Press F8 to exit. </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:silver;background:black"> </span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> </pre></div> <div class="shot"><pre><span style="color:black;background:teal">Press F8 to exit. </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Tim t</span><span style="color:silver;background:black"> </span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Nice to meet you, Tim</span> <span style="color:black;background:silver">t</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> </pre></div> <div class="shot"><pre><span style="color:black;background:teal">Press F8 to exit. </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Tim the Ench</span><span style="color:silver;background:black"> </span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Nice to meet you, Tim</span> <span style="color:black;background:silver">the Ench</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> </pre></div> <div class="shot"><pre><span style="color:black;background:teal">Press F8 to exit. </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Tim the Enchanter</span><span style="color:silver;background:black"> </span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Nice to meet you, Tim</span> <span style="color:black;background:silver">the Enchanter</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> </pre></div> <br clear="left"> <br> <h3><a name="lbcont">2.3. Modifying ListBox Content</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> 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. F8 exits. <br><br> Update the <a href="#frlb">previous program</a> with this code: <pre class="code"> def run(self): size = self.ui.get_cols_rows() while True: self.draw_screen( size ) keys = self.ui.get_input() if "f8" in keys: break for k in keys: if k == "window resize": size = self.ui.get_cols_rows() continue self.keypress( size, k ) def keypress(self, size, k): if k == "enter": widget, pos = self.listbox.get_focus() if not hasattr(widget,'get_edit_text'): return answer = self.new_answer( widget.get_edit_text() ) if pos == len(self.items)-1: self.items.append( answer ) self.items.append( self.new_question() ) else: self.items[pos+1:pos+2] = [answer] widget.set_edit_pos(0) self.listbox.set_focus( pos+2, coming_from='above' ) else: self.top.keypress( size, k )</pre> <ul> <li>In this version only the ENTER key receives special attention. When the user presses ENTER: <ul> <li>The widget in focus and its current position is retrieved by calling the <a href="reference.html#ListBox-get_focus">get_focus</a> function. <li>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 call <a href="reference.html#Edit-get_edit_text">get_edit_text</a>. <li>If the current position is at the end of the list, a response is appended followed by a new question. If the current position is not at the end then a previous response is replaced with an updated one. <li>The cursor position is moved to the far left by calling <a href="reference.html#Edit-set_edit_pos">set_edit_pos</a>. <li>Finally, the focus is moved down two positions to the next question by calling <a href="reference.html#ListBox-set_focus">set_focus</a>. </ul> <li>All other keys are passed to the top widget to handle. The ListBox widget does most of the hard work: <ul> <li>UP and DOWN will change the focus and/or scroll the widgets in the list box. <li>PAGE UP and PAGE DOWN will try to move the focus one screen up or down. <li>The cursor's column is maintained as best as possible when moving from one Edit widget to another. </ul> </ul> <div class="shot"><pre><span style="color:black;background:teal">Press F8 to exit. </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Abe </span> <span style="color:black;background:silver">Nice to meet you, Abe</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Bob</span><span style="color:silver;background:black"> </span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> </pre></div> <div class="shot"><pre><span style="color:black;background:teal">Press F8 to exit. </span> <span style="color:black;background:silver">Nice to meet you, Abe</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Bob </span> <span style="color:black;background:silver">Nice to meet you, Bob</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Carl </span> <span style="color:black;background:silver">Nice to meet you, Carl</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:silver;background:black"> </span><span style="color:black;background:silver"> </span> </pre></div> <div class="shot"><pre><span style="color:black;background:teal">Press F8 to exit. </span> <span style="color:black;background:silver">Nice to meet you, Bob</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Carl </span> <span style="color:black;background:silver">Nice to meet you, Carl</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver">Dave </span> <span style="color:black;background:silver">Nice to meet you, Dave</span><span style="color:black;background:silver"> </span> <span style="color:black;background:silver"> </span> <span style="color:black;background:silver">What is your name?</span><span style="color:black;background:silver"> </span> <span style="color:silver;background:black"> </span><span style="color:black;background:silver"> </span> </pre></div> <br clear="left"> <br> <h2>3. Zen of ListBox</h2> <h3><a name="lbscr">3.1. ListBox Focus and Scrolling</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> The <a href="reference.html#ListBox">ListBox</a> 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. <br><br> 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. <br><br> 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: <pre class="code">CONTENT = [ urwid.AttrWrap( w, None, 'reveal focus' ) for w in [ urwid.Text("This is a text string that is fairly long"), urwid.Divider("-"), urwid.Text("Short one"), urwid.Text("Another"), urwid.Divider("-"), urwid.Text("What could be after this?"), urwid.Text("The end."), ] ]</pre> <div class="shot"><pre><span style="color:white;background:black">Pressed: </span> <span style="color:black;background:teal">This is a text </span> <span style="color:black;background:teal">string that is </span> <span style="color:black;background:teal">fairly long </span> <span style="color:black;background:silver">---------------</span> <span style="color:black;background:silver">Short one </span> <span style="color:black;background:silver">Another </span> </pre></div> <div class="shot"><pre><span style="color:white;background:black">Pressed: down </span> <span style="color:black;background:silver">string that is </span> <span style="color:black;background:silver">fairly long </span> <span style="color:black;background:silver">---------------</span> <span style="color:black;background:silver">Short one </span> <span style="color:black;background:silver">Another </span> <span style="color:black;background:teal">---------------</span> </pre></div> <div class="shot"><pre><span style="color:white;background:black">Pressed: down </span> <span style="color:black;background:silver">fairly long </span> <span style="color:black;background:silver">---------------</span> <span style="color:black;background:silver">Short one </span> <span style="color:black;background:silver">Another </span> <span style="color:black;background:silver">---------------</span> <span style="color:black;background:teal">What could be </span> </pre></div> <div class="shot"><pre><span style="color:white;background:black">Pressed: down </span> <span style="color:black;background:silver">---------------</span> <span style="color:black;background:silver">Short one </span> <span style="color:black;background:silver">Another </span> <span style="color:black;background:silver">---------------</span> <span style="color:black;background:teal">What could be </span> <span style="color:black;background:teal">after this? </span> </pre></div> <div class="shot"><pre><span style="color:white;background:black">Pressed: up </span> <span style="color:black;background:teal">fairly long </span> <span style="color:black;background:silver">---------------</span> <span style="color:black;background:silver">Short one </span> <span style="color:black;background:silver">Another </span> <span style="color:black;background:silver">---------------</span> <span style="color:black;background:silver">What could be </span> </pre></div> <div class="shot"><pre><span style="color:white;background:black">Pressed: up </span> <span style="color:black;background:teal">string that is </span> <span style="color:black;background:teal">fairly long </span> <span style="color:black;background:silver">---------------</span> <span style="color:black;background:silver">Short one </span> <span style="color:black;background:silver">Another </span> <span style="color:black;background:silver">---------------</span> </pre></div> <br clear="left"> 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. <br><br> <div class="shot"><pre><span style="color:white;background:black">Pressed: </span> <span style="color:black;background:teal">string that is </span> <span style="color:black;background:teal">fairly long </span> <span style="color:black;background:silver">--------------------</span> <span style="color:black;background:silver">Short one </span> <span style="color:black;background:silver">Another </span> <span style="color:black;background:silver">--------------------</span> <span style="color:black;background:silver">What could be after </span> <span style="color:black;background:silver">this? </span> </pre></div> <div class="shot"><pre><span style="color:white;background:black">Pressed: </span> <span style="color:black;background:teal">This is a text string </span> <span style="color:black;background:teal">that is fairly long </span> <span style="color:black;background:silver">-------------------------</span> <span style="color:black;background:silver">Short one </span> <span style="color:black;background:silver">Another </span> <span style="color:black;background:silver">-------------------------</span> </pre></div> <div class="shot"><pre><span style="color:white;background:black">Pressed: </span> <span style="color:black;background:teal">This is a </span> <span style="color:black;background:teal">text string</span> <span style="color:black;background:teal">that is </span> <span style="color:black;background:teal">fairly long</span> <span style="color:black;background:silver">-----------</span> <span style="color:black;background:silver">Short one </span> <span style="color:black;background:silver">Another </span> <span style="color:black;background:silver">-----------</span> <span style="color:black;background:silver">What could </span> <span style="color:black;background:silver">be after </span> <span style="color:black;background:silver">this? </span> <span style="color:black;background:silver">The end. </span> </pre></div> <br clear="left"> <br><br> 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. <br clear="left"> <br> <h3><a name="lbdyn">3.2. Dynamic ListBox with List Walker</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> 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 <a href="reference.html#SimpleListWalker">SimpleListWalker</a> object to manage the list. <br><br> When the ListBox is <a href="reference.html#ListBox-render">rendering a canvas</a> or <a href="reference.html#ListBox-keypress">handling input</a> it will: <ol> <li>Call the <a href="reference.html#List_Walker_interface_definition-get_focus">get_focus</a> method of its list walker object. This method will return the focus widget and a position object. <li>Optionally call the <a href="reference.html#List_Walker_interface_definition-get_prev">get_prev</a> 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. <li>Optionally call the <a href="reference.html#List_Walker_interface_definition-get_next">get_next</a> method of its List Walker object one or more times, similarly, to collect widgets and position objects "below" the focus position. <li>Optionally call the <a href="reference.html#List_Walker_interface_definition-set_focus">set_focus</a> method passing one of the position objects returned in the previous steps. </ol> 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. <br><br> 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. <br><br> 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 <a href="reference.html#List_Walker_interface_definition">List Walker interface</a>. <br><br> The <a href="fib.py.html">fib.py</a> 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. <br><br> The <a href="edit.py.html">edit.py</a> 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. <br><br> The <a href="browse.py.html">browse.py</a> 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". <br clear="left"> <br> <h3><a name="lbfocus">3.3. Setting the Focus</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> The easiest way to change the current ListBox focus is to call the <a href="reference.html#ListBox-set_focus">set_focus</a> 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. <br><br> 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. <br><br> 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: <ul> <li>Display the new focus at the bottom of the ListBox if coming_from is "above". <li>Display the new focus at the top of the ListBox if coming_from is "below". <li>Display the new focus in the middle of the ListBox if coming_from is None. </ul> If you know exactly where you want to display the new focus widget within the ListBox you may call <a href="reference.html#ListBox-set_focus_valign">set_focus_valign</a>. 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. <br clear="left"> <br> <h2>4. Combining Widgets</h2> <h3><a name="pile">4.1. Piling Widgets</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> <a href="reference.html#Pile">Pile</a> 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. <br><br> 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 <a href="reference.html#Pile-set_focus">set_focus</a>. <br clear="left"> <br> <h3><a name="cols">4.2. Dividing into Columns</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> <a href="reference.html#Columns">Columns</a> 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. <br><br> 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 <a href="reference.html#Columns-set_focus">set_focus</a> method may be used to select the focus column. <br clear="left"> <br> <h3><a name="grid">4.3. GridFlow Arrangement</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> The <a href="reference.html#GridFlow">GridFlow</a> widget is a flow widget designed for use with <a href="reference.html#Button">Button</a>, <a href="reference.html#CheckBox">CheckBox</a> and <a href="reference.html#RadioButton">RadioButton</a> widgets. It renders all the widgets it contains the same width and it arranges them from left to right and top to bottom. <br><br> 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. <br clear="left"> <br> <h3><a name="overlay">4.4. Overlay Widgets</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> The <a href="reference.html#Overlay">Overlay</a> 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. <br><br> The Overlay widget always treats the top widget as the one in focus. All keyboard input will be passed to the top widget. <br><br> If you want to use a flow flow widget for the top widget, first wrap the flow widget with a <a href="reference.html#Filler">Filler</a> widget. <br clear="left"> <br> <h2>5. Creating Custom Widgets</h2> <h3><a name="wmod">5.1. Modifying Existing Widgets</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> 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. <br><br> The <a href="reference.html#WidgetWrap">WidgetWrap</a> 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. <br><br> This is an example of a custom widget that uses WidgetWrap: <pre class="code">class QuestionnaireItem( urwid.WidgetWrap ): def __init__(self): self.options = [] unsure = urwid.RadioButton( self.options, "Unsure" ) yes = urwid.RadioButton( self.options, "Yes" ) no = urwid.RadioButton( self.options, "No" ) display_widget = urwid.GridFlow( [unsure, yes, no], 15, 3, 1, 'left' ) urwid.WidgetWrap.__init__(self, display_widget) def get_state(self): for o in self.options: if o.get_state() is True: return o.get_label()</pre> The above code creates a group of RadioButtons and provides a method to query the state of the buttons. <br><br> Wrapped widgets may also override the standard widget methods. These methods are described in following sections. <br clear="left"> <br> <h3><a name="wanat">5.2. Anatomy of a Widget</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> Any object that follows the <a href="reference.html#Widget_interface_definition">Widget interface definition</a> may be used as a widget. Box widgets must implement <a href="reference.html#Widget_interface_definition-selectable">selectable</a> and <a href="reference.html#Widget_interface_definition-render">render</a> methods, and flow widgets must implement selectable, render and <a href="reference.html#Widget_interface_definition-rows">rows</a> methods. <pre class="code">class Pudding( urwid.FlowWidget ): def selectable( self ): return False def rows( self, (maxcol,), focus=False ): return 1 def render( self, (maxcol,), focus=False ): num_pudding = maxcol / len("Pudding") return urwid.TextCanvas(["Pudding"*num_pudding]) class BoxPudding( urwid.BoxWidget ): def selectable( self ): return False def render( self, (maxcol, maxrow), focus=False ): num_pudding = maxcol / len("Pudding") return urwid.TextCanvas( ["Pudding"*num_pudding] * maxrow)</pre> 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. <br><br> It is not strictly necessary to inherit from <a href="reference.html#FlowWidget">BoxWidget</a> or <a href="reference.html#FlowWidget">FlowWidget</a>, but doing so does add some documentation to your code. <br><br> 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. <br><br> In most cases it is easier to let other widgets handle the rendering and row calculations for you: <pre class="code">class NewPudding( urwid.FlowWidget ): def selectable( self ): return False def rows( self, (maxcol,), focus=False ): w = self.display_widget( (maxcol,), focus ) return w.rows( (maxcol,), focus ) def render( self, (maxcol,), focus=False ): w = self.display_widget( (maxcol,), focus ) return w.render( (maxcol,), focus ) def display_widget( self, (maxcol,), focus ): num_pudding = maxcol / len("Pudding") return urwid.Text( "Pudding"*num_pudding )</pre> 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. <br><br> 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. <br><br> It is possible to create a widget that will behave as either a flow widget or box widget depending on what is required: <pre class="code">class MultiPudding( urwid.Widget ): def selectable( self ): return False def rows( self, (maxcol,), focus=False ): return 1 def render( self, size, focus=False ): if len(size) == 1: (maxcol,) = size maxrow = 1 else: (maxcol, maxrow) = size num_pudding = maxcol / len("Pudding") return urwid.TextCanvas( ["Pudding"*num_pudding] * maxrow )</pre> 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. <br clear="left"> <br> <h3><a name="wsel">5.3. Creating Selectable Widgets</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> 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 <a href="reference.html#Widget_interface_definition-keypress">keypress</a> method to handle keyboard input. <pre class="code">class SelectablePudding( urwid.FlowWidget ): def __init__( self ): self.pudding = "pudding" def selectable( self ): return True def rows( self, (maxcol,), focus=False ): return 1 def render( self, (maxcol,), focus=False ): num_pudding = maxcol / len(self.pudding) pudding = self.pudding if focus: pudding = pudding.upper() return urwid.TextCanvas( [pudding*num_pudding] ) def keypress( self, (maxcol,), key ): if len(key)>1: return key if key.lower() in self.pudding: # remove letter from pudding n = self.pudding.index(key.lower()) self.pudding = self.pudding[:n]+self.pudding[n+1:] if not self.pudding: self.pudding = "pudding" else: return key</pre> 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. <br><br> 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. <br clear="left"> <br> <h3><a name="wcur">5.4. Widgets Displaying the Cursor</a> <span class="back">[<a href="#top">back to top</a>]</span></h3> Widgets that display the cursor must implement the <a href="reference.html#Widget_interface_definition-get_cursor_coords">get_cursor_coords</a> 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. <pre class="code">class CursorPudding( urwid.FlowWidget ): def __init__( self ): self.cursor_col = 0 def selectable( self ): return True def rows( self, (maxcol,), focus=False ): return 1 def render( self, (maxcol,), focus=False ): num_pudding = maxcol / len("Pudding") cursor = None if focus: cursor = self.get_cursor_coords((maxcol,)) return urwid.TextCanvas( ["Pudding"*num_pudding], [], cursor ) def get_cursor_coords( self, (maxcol,) ): col = min(self.cursor_col, maxcol-1) return col, 0 def keypress( self, (maxcol,), key ): if key == 'left': col = self.cursor_col -1 elif key == 'right': col = self.cursor_col +1 else: return key self.cursor_x = max(0, min( maxcol-1, col ))</pre> 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. <br><br>A widget displaying a cursor may choose to implement <a href="reference.html#Widget_interface_definition-get_pref_col">get_pref_col</a>. This method returns the preferred column for the cursor, and is called when the focus is moving up or down off this widget. <br><br> Another optional method is <a href="reference.html#Widget_interface_definition-move_cursor_to_coords">move_cursor_to_coords</a>. 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. <pre class="code"> def get_pref_col( self, (maxcol,) ): return self.cursor_x def move_cursor_to_coords( self, (maxcol,), col, row ): assert row == 0 self.cursor_x = col return True</pre> <br clear="left"> <br> </body> </html>