Display Modules

class urwid.BaseScreen

Base class for Screen classes (raw_display.Screen, .. etc)

clear() None

Clear the screen if possible.

Force the screen to be completely repainted on the next call to draw_screen().

get_cols_rows() tuple[int, int]

Return the terminal dimensions (num columns, num rows).

Default (fallback) is 80x24.

register_palette(palette: Iterable[tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str] | tuple[str, str, str, str, str, str]]) None

Register a set of palette entries.

palette – a list of (name, like_other_name) or (name, foreground, background, mono, foreground_high, background_high) tuples

The (name, like_other_name) format will copy the settings from the palette entry like_other_name, which must appear before this tuple in the list.

The mono and foreground/background_high values are optional ie. the second tuple format may have 3, 4 or 6 values. See register_palette_entry() for a description of the tuple values.

register_palette_entry(name: str | None, foreground: str, background: str, mono: str | None = None, foreground_high: str | None = None, background_high: str | None = None) None

Register a single palette entry.

name – new entry/attribute name

foreground – a string containing a comma-separated foreground color and settings

Color values: ‘default’ (use the terminal’s default foreground), ‘black’, ‘dark red’, ‘dark green’, ‘brown’, ‘dark blue’, ‘dark magenta’, ‘dark cyan’, ‘light gray’, ‘dark gray’, ‘light red’, ‘light green’, ‘yellow’, ‘light blue’, ‘light magenta’, ‘light cyan’, ‘white’

Settings: ‘bold’, ‘underline’, ‘blink’, ‘standout’, ‘strikethrough’

Some terminals use ‘bold’ for bright colors. Most terminals ignore the ‘blink’ setting. If the color is not given then ‘default’ will be assumed.

background – a string containing the background color

Background color values: ‘default’ (use the terminal’s default background), ‘black’, ‘dark red’, ‘dark green’, ‘brown’, ‘dark blue’, ‘dark magenta’, ‘dark cyan’, ‘light gray’

mono – a comma-separated string containing monochrome terminal settings (see “Settings” above.)

None = no terminal settings (same as ‘default’)

foreground_high – a string containing a comma-separated foreground color and settings, standard foreground colors (see “Color values” above) or high-colors may be used

High-color example values: ‘#009’ (0% red, 0% green, 60% red, like HTML colors) ‘#fcc’ (100% red, 80% green, 80% blue) ‘g40’ (40% gray, decimal), ‘g#cc’ (80% gray, hex), ‘#000’, ‘g0’, ‘g#00’ (black), ‘#fff’, ‘g100’, ‘g#ff’ (white) ‘h8’ (color number 8), ‘h255’ (color number 255)

None = use foreground parameter value

background_high – a string containing the background color, standard background colors (see “Background colors” above) or high-colors (see “High-color example values” above) may be used

None = use background parameter value

run_wrapper(fn, *args, **kwargs)

Start the screen, call a function, then stop the screen. Extra arguments are passed to start.

Deprecated in favor of calling start as a context manager.

start(*args, **kwargs) StoppingContext

Set up the screen. If the screen has already been started, does nothing.

May be used as a context manager, in which case stop() will automatically be called at the end of the block:

with screen.start():

You shouldn’t override this method in a subclass; instead, override _start().

RAW display

class urwid.display.raw.Screen(input: ~typing.TextIO = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>, output: ~typing.TextIO = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, bracketed_paste_mode=False)

Initialize a screen that directly prints escape codes to an output terminal.

bracketed_paste_mode – enable bracketed paste mode in the host terminal.

If the host terminal supports it, the application will receive begin paste and end paste keystrokes when the user pastes text.

get_cols_rows() tuple[int, int]

Return the terminal dimensions (num columns, num rows).

get_input_descriptors() list[socket.socket | IO | int]

Return a list of integer file descriptors that should be polled in external event loops to check for user input.

Use this method if you are implementing your own event loop.

This method is only called by hook_event_loop, so if you override that, you can safely ignore this.

hook_event_loop(event_loop: EventLoop, callback: Callable[[list[str], list[int]], Any]) None

Register the given callback with the event loop, to be called with new input whenever it’s available. The callback should be passed a list of processed keys and a list of unprocessed keycodes.

Subclasses may wish to use parse_input to wrap the callback.

signal_init() None

Called in the startup of run wrapper to set the SIGWINCH and SIGTSTP signal handlers.

Override this function to call from main thread in threaded applications.

signal_restore() None

Called in the finally block of run wrapper to restore the SIGTSTP, SIGCONT and SIGWINCH signal handlers.

Override this function to call from main thread in threaded applications.

unhook_event_loop(event_loop: EventLoop) None

Remove any hooks added by hook_event_loop.

Curses display

class urwid.display.curses.Screen
clear() None

Force the screen to be completely repainted on the next call to draw_screen().

draw_screen(size: tuple[int, int], canvas: Canvas) None

Paint screen with rendered canvas.

get_cols_rows() tuple[int, int]

Return the terminal dimensions (num columns, num rows).

get_input(raw_keys: Literal[False]) list[str]
get_input(raw_keys: Literal[True]) tuple[list[str], list[int]]

Return pending input as a list.

raw_keys – return raw keycodes as well as translated versions

This function will immediately return all the input since the last time it was called. If there is no input pending it will wait before returning an empty list. The wait time may be configured with the set_input_timeouts function.

If raw_keys is False (default) this function will return a list of keys pressed. If raw_keys is True this function will return a ( keys pressed, raw keycodes ) tuple instead.

Examples of keys returned:

  • ASCII printable characters: “ “, “a”, “0”, “A”, “-”, “/”

  • ASCII control characters: “tab”, “enter”

  • Escape sequences: “up”, “page up”, “home”, “insert”, “f1”

  • Key combinations: “shift f1”, “meta a”, “ctrl b”

  • Window events: “window resize”

When a narrow encoding is not enabled:

  • “Extended ASCII” characters: “xa1”, “xb2”, “xfe”

When a wide encoding is enabled:

  • Double-byte characters: “xa1xea”, “xb2xd4”

When utf8 encoding is enabled:

  • Unicode characters: u”u00a5”, u’u253c”

Examples of mouse events returned:

  • Mouse button press: (‘mouse press’, 1, 15, 13),

    (‘meta mouse press’, 2, 17, 23)

  • Mouse button release: (‘mouse release’, 0, 18, 13),

    (‘ctrl mouse release’, 0, 17, 23)

set_input_timeouts(max_wait: float | None = None, complete_wait: float = 0.1, resize_wait: float = 0.1)

Set the get_input timeout values. All values have a granularity of 0.1s, ie. any value between 0.15 and 0.05 will be treated as 0.1 and any value less than 0.05 will be treated as 0. The maximum timeout value for this module is 25.5 seconds.

max_wait – amount of time in seconds to wait for input when

there is no input pending, wait forever if None

complete_wait – amount of time in seconds to wait when

get_input detects an incomplete escape sequence at the end of the available input

resize_wait – amount of time in seconds to wait for more input

after receiving two screen resize requests in a row to stop urwid from consuming 100% cpu during a gradual window resize operation

set_mouse_tracking(enable: bool = True) None

Enable mouse tracking.

After calling this function get_input will include mouse click events along with keystrokes.

WEB display

class urwid.display.web.Screen
clear() None

Force the screen to be completely repainted on the next call to draw_screen().

(does nothing for web_display)

draw_screen(size: tuple[int, int], canvas: Canvas) None

Send a screen update to the client.

get_cols_rows() tuple[int, int]

Return the screen size.

get_input(raw_keys: Literal[False]) list[str]
get_input(raw_keys: Literal[True]) tuple[list[str], list[int]]

Return pending input as a list.

register_palette(palette) None

Register a list of palette entries.

palette – list of (name, foreground, background) or

(name, same_as_other_name) palette entries.

calls self.register_palette_entry for each item in l

register_palette_entry(name: str | None, foreground: str, background: str, mono: str | None = None, foreground_high: str | None = None, background_high: str | None = None) None

Register a single palette entry.

name – new entry/attribute name foreground – foreground colour background – background colour mono – monochrome terminal attribute

See curses_display.register_palette_entry for more info.

set_mouse_tracking(enable: bool = True) None

Not yet implemented

start() StoppingContext

This function reads the initial screen size, generates a unique id and handles cleanup when fn exits.

web_display.set_preferences(..) must be called before calling this function for the preferences to take effect

stop() None

Restore settings and clean up.

tty_signal_keys(*args, **vargs)

Do nothing.

HTML fragment

class urwid.display.html_fragment.HtmlGenerator
draw_screen(size: tuple[int, int], canvas: Canvas) None

Create an html fragment from the render object. Append it to HtmlGenerator.fragments list.

get_cols_rows()

Return the next screen size in HtmlGenerator.sizes.

get_input(raw_keys: Literal[False]) list[str]
get_input(raw_keys: Literal[True]) tuple[list[str], list[int]]

Return the next list of keypresses in HtmlGenerator.keys.

urwid.display.html_fragment.screenshot_init(sizes: list[tuple[int, int]], keys: list[list[str]]) None

Replace curses_display.Screen and raw_display.Screen class with HtmlGenerator.

Call this function before executing an application that uses curses_display.Screen to have that code use HtmlGenerator instead.

sizes – list of ( columns, rows ) tuples to be returned by each call

to HtmlGenerator.get_cols_rows()

keys – list of lists of keys to be returned by each call to

HtmlGenerator.get_input()

Lists of keys may include “window resize” to force the application to call get_cols_rows and read a new screen size.

For example, the following call will prepare an application to:
  1. start in 80x25 with its first call to get_cols_rows()

  2. take a screenshot when it calls draw_screen(..)

  3. simulate 5 “down” keys from get_input()

  4. take a screenshot when it calls draw_screen(..)

  5. simulate keys “a”, “b”, “c” and a “window resize”

  6. resize to 20x10 on its second call to get_cols_rows()

  7. take a screenshot when it calls draw_screen(..)

  8. simulate a “Q” keypress to quit the application

screenshot_init( [ (80,25), (20,10) ],

[ [“down”]*5, [“a”,”b”,”c”,”window resize”], [“Q”] ] )

urwid.display.html_fragment.screenshot_collect() list[str]

Return screenshots as a list of HTML fragments.

LCD display

class urwid.display.lcd.LCDScreen

Base class for LCD-based screens.

get_cols_rows()

Return the terminal dimensions (num columns, num rows).

Default (fallback) is 80x24.

class urwid.display.lcd.CFLCDScreen(device_path: str, baud: int)

Common methods for Crystal Fonts LCD displays

device_path – eg. ‘/dev/ttyUSB0’ baud – baud rate

exception InvalidPacket
exception MoreDataRequired
class urwid.display.lcd.CF635Screen(device_path: str, baud: int = 115200, repeat_delay: float = 0.5, repeat_next: float = 0.125, key_map: Iterable[str] = ('up', 'down', 'left', 'right', 'enter', 'esc'))

Crystal Fontz 635 display

20x4 character display + cursor no foreground/background colors or settings supported

see CGROM for list of close unicode matches to characters available

6 button input up, down, left, right, enter (check mark), exit (cross)

device_path – eg. ‘/dev/ttyUSB0’ baud – baud rate repeat_delay – seconds to wait before starting to repeat keys repeat_next – time between each repeated key key_map – the keys to send for this device’s buttons

get_input_descriptors() list[int]

return the fd from our serial device so we get called on input and responses

get_input_nonblocking() tuple[None, list[str], list[int]]

Return a (next_input_timeout, keys_pressed, raw_keycodes) tuple.

The protocol for our device requires waiting for acks between each command, so this method responds to those as well as key press and release events.

Key repeat events are simulated here as the device doesn’t send any for us.

raw_keycodes are the bytes of messages we received, which might not seem to have any correspondence to keys_pressed.

program_cgram(index: int, data: Sequence[int]) None

Program character data.

Characters available as chr(0) through chr(7), and repeated as chr(8) through chr(15).

index – 0 to 7 index of character to program

data – list of 8, 6-bit integer values top to bottom with MSB on the left side of the character.

set_backlight(value: int) None

Set backlight brightness

value – 0 to 100

set_cursor_style(style: Literal[1, 2, 3, 4]) None
style – CURSOR_BLINKING_BLOCK, CURSOR_UNDERSCORE,

CURSOR_BLINKING_BLOCK_UNDERSCORE or CURSOR_INVERTING_BLINKING_BLOCK

set_lcd_contrast(value: int) None

value – 0 to 255

set_led_pin(led: Literal[0, 1, 2, 3], rg: Literal[0, 1], value: int) None

led – 0 to 3 rg – 0 for red, 1 for green value – 0 to 100

class urwid.display.lcd.KeyRepeatSimulator(repeat_delay: float, repeat_next: float)

Provide simulated repeat key events when given press and release events.

If two or more keys are pressed disable repeating until all keys are released.

repeat_delay – seconds to wait before starting to repeat keys repeat_next – time between each repeated key

next_event() tuple[float, str] | None

Return (remaining, key) where remaining is the number of seconds (float) until the key repeat event should be sent, or None if no events are pending.

sent_event() None

Cakk this method when you have sent a key repeat event so the timer will be reset for the next event