Urwid Tutorial
Note: This tutorial requires Urwid 1.8.5 or later.
1. Hello World
|
2. Conversation
|
1. Hello World
This program displays the string "Hello World" in the top left corner
of the screen and waits for a keypress before exiting.
import urwid.curses_display
import urwid
ui = urwid.curses_display.Screen()
def run():
canvas = urwid.Canvas( ["Hello World"] )
ui.draw_screen( (20, 1), canvas )
while not ui.get_input():
pass
ui.run_wrapper( run )
- The curses_display.Screen
class provides access to the curses library. Its member function
run_wrapper 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.
- A Canvas is created
containing one row with the string "Hello World".
- The canvas is passed to the
draw_screen function along
with a fixed screen size of 20 columns and 1 row. It is likely that the
terminal window this program is run from is larger than 20 by 1, so the
text will appear in the top left corner.
- The get_input function
is then called until it returns something. It must be called in a loop
because it will time out after one second and return an empty list.
Creating canvases directly 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.
This program displays the string "Hello World" in the center of the screen
and waits for a keypress before exiting.
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 )
- get_cols_rows
is used to get the dimensions from the terminal and store them as "cols"
and "rows".
- A Text widget is created containing
the string "Hello World". It is set to display with "center" alignment.
Text widgets are a kind of FlowWidget.
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.
- A Filler widget is created to
wrap the text widget. Filler widgets are a kind of
BoxWidget. 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.
- A canvas is created by calling the
render 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.
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.
This program displays the string "Hello World" in the center of the screen.
It uses different attributes used for the text, the space on either side
of the text and the space above and below the text. It then and waits for
a keypress before exiting.
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 )
- After creating the
curses_display.Screen object
and before calling run_wrapper,
register_palette is called
to set up some attributes:
- "banner" is black text on a light gray background, or reversed attributes
and underlined in monochrome mode
- "streak" is black text on a dark red background, or reversed attributes
in monochrome mode
- "bg" is black text on a dark blue background, or normal in
monochrome mode
- 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.
- An AttrWrap 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.
- A Filler widget is created to
wrap the AttrWrap widget and fill the rows above and below it.
- A second AttrWrap widget is created to
wrap the filler widget with attribute "bg".
- A canvas is created by calling the
render function on the topmost
widget.
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.
This program displays the string "Hello World" in the center of the screen.
It uses different attributes used 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.
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 )
The get_input 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
because it is easy to users to forget that Caps Lock is on.
2. Conversation
This program asks for your name then responds "Nice to meet you, (your name)."
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
fill.keypress( (cols, rows), k )
ui.run_wrapper( run )
- 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.
- A Filler widget is created to wrap
the edit widget. Its render
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.
- Keys are processed one at a time. Most keys are sent to the Filler widget's
keypress function which will
call the Edit widget's keypress
function to handle the key.
- Once the ENTER key is pressed the wrapped object in the Filler widget
is changed to a reply text.
- Any keypress then causes 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.
What is your name?
Arthur, King of the
Britons
Nice to meet you,
Arthur, King of the
Britons.
This program asks for your name and responds "Nice to meet you, (your name)"
while you type your name. F1 exits.
import urwid.curses_display
import urwid
class Conversation:
def __init__(self):
self.items = [ self.new_question() ]
self.listbox = urwid.ListBox( self.items )
instruct = urwid.Text("Press F1 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', 'dark blue', '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 "f1" 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()
- In the __init__ function a list called self.items is created. It
contains an Edit widget with the caption "What is your name?".
- A ListBox 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.
- A Frame 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.
- When a key is pressed the reply text is inserted or updated in
self.items. This updated text will be displayed by self.listbox.
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.
Press F1 to exit.
What is your name?
Press F1 to exit.
What is your name?
Tim t
Nice to meet you, Tim
t
Press F1 to exit.
What is your name?
Tim the Ench
Nice to meet you, Tim
the Ench
Press F1 to exit.
What is your name?
Tim the Enchanter
Nice to meet you, Tim
the Enchanter
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. F1 exits.
Update the 2.2 program with this code:
def run(self):
size = self.ui.get_cols_rows()
while True:
self.draw_screen( size )
keys = self.ui.get_input()
if "f1" 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,'edit_text'):
return
answer = self.new_answer( widget.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]
self.listbox.set_focus( pos+2, coming_from='above' )
widget, pos = self.listbox.get_focus()
widget.set_edit_pos(0)
else:
self.top.keypress( size, k )
- In this version only the ENTER key receives special attention. 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 would cause the
program to crash.
- 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.
- The focus is moved down two positions to the next question by calling
set_focus.
- Finally, the cursor position within the new focus widget it moved to
the far left by calling
set_edit_pos.
- 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.
The ListBox widget tries to do the most sensible thing when scrolling and
changing focus. When the widgets displayed are all unselectable
the ListBox widget will always scroll. When some widgets
are selectable it will try changing focus before scrolling, possibly
scrolling a few lines to bring in a full selectable widget. When all the
widgets are selectable it will only scroll when the cursor reaches the
top or bottom edge.
Press F1 to exit.
What is your name?
Abe
Nice to meet you, Abe
What is your name?
Bob
Press F1 to exit.
Nice to meet you, Abe
What is your name?
Bob
Nice to meet you, Bob
What is your name?
Carl
Nice to meet you, Carl
What is your name?
Press F1 to exit.
Nice to meet you, Bob
What is your name?
Carl
Nice to meet you, Carl
What is your name?
Dave
Nice to meet you, Dave
What is your name?