Edit text using Python and curses Textbox widget?

Keith picture Keith · Jan 3, 2011 · Viewed 14.4k times · Source

Has anybody got a working example of using the curses.textpad.Textbox widget to edit existing text? This is, of course, in a Linux terminal (e.g. xterm).

Answer

Hylix picture Hylix · Mar 16, 2011

Found this there is several minutes

import curses
import curses.textpad

stdscr = curses.initscr()
# don't echo key strokes on the screen
curses.noecho()
# read keystrokes instantly, without waiting for enter to ne pressed
curses.cbreak()
# enable keypad mode
stdscr.keypad(1)
stdscr.clear()
stdscr.refresh()
win = curses.newwin(5, 60, 5, 10)
tb = curses.textpad.Textbox(win)
text = tb.edit()
curses.beep()
win.addstr(4,1,text.encode('utf_8'))

I also made a function to make a textbox:

def maketextbox(h,w,y,x,value="",deco=None,underlineChr=curses.ACS_HLINE,textColorpair=0,decoColorpair=0):
    nw = curses.newwin(h,w,y,x)
    txtbox = curses.textpad.Textbox(nw)
    if deco=="frame":
        screen.attron(decoColorpair)
        curses.textpad.rectangle(screen,y-1,x-1,y+h,x+w)
        screen.attroff(decoColorpair)
    elif deco=="underline":
        screen.hline(y+1,x,underlineChr,w,decoColorpair)

    nw.addstr(0,0,value,textColorpair)
    nw.attron(textColorpair)
    screen.refresh()
    return txtbox

To use it just do:

foo = maketextbox(1,40, 10,20,"foo",deco="underline",textColorpair=curses.color_pair(0),decoColorpair=curses.color_pair(1))
text = foo.edit()