How to enter a word into the ncurses screen?

At first I tried to use the raw_input() function, but found it in ncurses compatible.
Then I tried the window.getch() function, I can print and show characters on the screen, but I can not implement the input. How can I enter a word in ncurses and use the if expression to evaluate it?

For example, I want to implement this in ncurses :

 import ncurses stdscr = curses.initscr() # ???_input = "cool" # this is the missing input method I want to know if ???_input == "cool": stdscr.addstr(1,1,"Super cool!") stdscr.refresh() stdscr.getch() curses.endwin() 
+5
source share
1 answer

The raw_input( ) function does not work in curses mode, the getch() method returns an integer; it is the ASCII code of the pressed key. Will not work if you want to scan a line from the prompt. You can use the getstr function:

window.getstr([y, x])

Read a line from the user with the ability to edit a primitive line.

User input

There is also a method to extract the entire string, getstr()

 curses.echo() # Enable echoing of characters # Get a 15-character string, with the cursor on the top line s = stdscr.getstr(0,0, 15) 

And I wrote a raw_input function as shown below:

 def my_raw_input(stdscr, r, c, prompt_string): curses.echo() stdscr.addstr(r, c, prompt_string) stdscr.refresh() input = stdscr.getstr(r + 1, c, 20) return input # ^^^^ reading input at next line 

name it choice = my_raw_input(stdscr, 5, 5, "cool or hot?")

Edit: Here is a working example:

 if __name__ == "__main__": stdscr = curses.initscr() stdscr.clear() choice = my_raw_input(stdscr, 2, 3, "cool or hot?").lower() if choice == "cool": stdscr.addstr(5,3,"Super cool!") elif choice == "hot": stdscr.addstr(5, 3," HOT!") else: stdscr.addstr(5, 3," Invalid input") stdscr.refresh() stdscr.getch() curses.endwin() 

output:

enter image description here

+13
source

Source: https://habr.com/ru/post/1014903/


All Articles