问题描述
我试图先使用raw_input()
函数,但是发现它与ncurses兼容.
然后我尝试了window.getch()
函数,我可以在屏幕上键入和显示字符,但是无法实现输入.如何在ncurses
中输入单词并可以使用if语句对其进行评估?
I was trying to use raw_input()
function first, but find it in compatible with ncurses.
Then I tried window.getch()
function, I can type and show characters on screen, but can't realize input. How can I input a word in ncurses
and can use if statement to evaluate it?
例如,我想在ncurses
中实现这一点:
For example, I wanna realize 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()
推荐答案
函数raw_input( )
在curses模式下不起作用,getch()
方法返回一个整数.它代表所按下键的ASCII码.如果您想从提示符下扫描字符串,则将不起作用.您可以使用getstr
函数:
Function raw_input( )
doesn't works in curses mode, The getch()
method returns an integer; it represents the ASCII code of the key pressed. The will not work if you wants to scan string from prompt. You can make use of getstr
function:
还有一种检索整个字符串的方法,getstr()
There’s also a method to retrieve an 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)
然后我编写了raw_input函数,如下所示:
And I wrote raw_input function as 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
称为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()
输出:
这篇关于如何在ncurses屏幕中输入单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!