我试图首先使用raw_input()函数,但发现它与ncurses兼容.
然后我尝试了window.getch()功能,我可以在屏幕上输入和显示字符,但无法实现输入.我如何输入一个单词ncurses并可以使用if语句来评估它?
例如,我想知道这一点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()
Run Code Online (Sandbox Code Playgroud)
Gri*_*han 13
函数raw_input( )在curses模式下不起作用,该getch()方法返回一个整数; 它表示按下的键的ASCII码.如果要从提示符扫描字符串,则无效.你可以使用getstr功能:
window.getstr([y, x])使用原始行编辑功能从用户读取字符串.
用户输入
还有一种方法来检索整个字符串,
getstr()Run Code Online (Sandbox Code Playgroud)curses.echo() # Enable echoing of characters # Get a 15-character string, with the cursor on the top line s = stdscr.getstr(0,0, 15)
我写了raw_input函数如下:
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
Run Code Online (Sandbox Code Playgroud)
称之为 choice = my_raw_input(stdscr, 5, 5, "cool or hot?")
编辑:这是工作示例:
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()
Run Code Online (Sandbox Code Playgroud)
输出: