Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using backspace with getch() in python curses

Tags:

python

curses

I want the user to be able to type with each character, the way that getch() works. I also have echo() turned on because I want to print out each character that the user types. However, I also want the user to be able to hit backspace and have the key that he pressed before he hit backspace to be deleted from the screen, just like how backspace works in a text editor. How can I do this? I am using python 3.6 with the curses lib (obviously). If you want to see my code so far, here it is:

import curses

# ----- INIT -----
stdscr = curses.initscr()
curses.cbreak()
stdscr.keypad(1)

# ----- PRINT -----
text = "Hello world"
stdscr.addstr(1, 0, text + "\n")
stdscr.refresh()

# ----- MAIN LOOP ------
while 1:
    c = stdscr.getch()
    if c == ord('q'):
        break

# ----- RESET TERMINAL -----
curses.echo()
curses.nocbreak()
stdscr.keypad(1)
curses.endwin()
like image 446
Matt X Avatar asked Apr 11 '26 12:04

Matt X


1 Answers

You could do something like this: disable echo, use explicit library calls to echo the characters other than the usual choices for "backspace":

import curses

# ----- INIT -----
stdscr = curses.initscr()
curses.cbreak()
curses.noecho()
stdscr.keypad(1)

# ----- PRINT -----
text = "Hello world"
stdscr.addstr(1, 0, text + "\n")
stdscr.refresh()

# ----- MAIN LOOP ------
while 1:
    c = stdscr.getch()
    if c == ord('q'):
        break
    if c == 8 or c == 127 or c == curses.KEY_BACKSPACE:
        stdscr.addstr("\b \b")
    else:
        stdscr.addch(c)

# ----- RESET TERMINAL -----
curses.echo()
curses.nocbreak()
stdscr.keypad(1)
curses.endwin()

The Python curses reference does not go into much detail for addch, but since it is a wrapper around curses, you can read its manual page about the way the literal backspace \b is interpreted to make the cursor move backward. The example then writes a space (erasing whatever was there), and then moves the cursor back onto the empty space.

like image 162
Thomas Dickey Avatar answered Apr 14 '26 00:04

Thomas Dickey