2 min read

Python Curses Module

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling. It allows you to create text-based user interfaces (TUI).

Note: On Windows, the curses module is not included in the standard library. You can install it using pip install windows-curses.

Importing the Module

import curses

Basic Usage

The curses.wrapper() function simplifies the initialization and cleanup of curses applications. It handles initializing the library, creating a window, and resetting the terminal state upon exception or exit.

import curses

def main(stdscr):
    # Clear screen
    stdscr.clear()

    # Add text at (0, 0)
    stdscr.addstr(0, 0, "Hello, Curses!")

    # Refresh to update the screen
    stdscr.refresh()

    # Wait for a key press
    stdscr.getkey()

curses.wrapper(main)

Windows and Pads

Windows

Windows are the basic abstraction in curses. stdscr is the standard screen window. You can create new windows using curses.newwin(height, width, begin_y, begin_x).

import curses

def main(stdscr):
    begin_x = 20; begin_y = 7
    height = 5; width = 40
    win = curses.newwin(height, width, begin_y, begin_x)
    win.addstr(0, 0, "I am a new window")
    win.refresh()
    stdscr.getkey()

curses.wrapper(main)

Pads

Pads are like windows but can be larger than the screen. You display a section of a pad on the screen.

import curses

def main(stdscr):
    pad = curses.newpad(100, 100)
    # Fill the pad
    for y in range(0, 99):
        for x in range(0, 99):
            pad.addch(y, x, ord('a') + (x*x+y*y) % 26)

    # Display a section of the pad
    # refresh(pad_min_y, pad_min_x, screen_min_y, screen_min_x, screen_max_y, screen_max_x)
    pad.refresh(0, 0, 5, 5, 20, 75)
    stdscr.getkey()

curses.wrapper(main)

Colors

To use colors, you must call curses.start_color() (handled by wrapper). You define color pairs and use them.

import curses

def main(stdscr):
    # Check if color is supported
    if curses.has_colors():
        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)

        # Use color pair 1
        stdscr.addstr(0, 0, "Red text on white background", curses.color_pair(1))
        stdscr.refresh()
        stdscr.getkey()

curses.wrapper(main)

User Input

getch() returns the integer code of the key pressed. getkey() returns the character string.

import curses

def main(stdscr):
    stdscr.addstr("Press 'q' to quit\n")
    while True:
        key = stdscr.getkey()
        stdscr.addstr(f"Key pressed: {key}\n")
        if key == 'q':
            break

curses.wrapper(main)

Attributes

You can display text with attributes like bold, underline, etc.

stdscr.addstr(0, 0, "Bold Text", curses.A_BOLD)
stdscr.addstr(1, 0, "Underlined Text", curses.A_UNDERLINE)

programming/python/python