如何在ncurses屏幕上输入单词?

2024-04-26 14:07:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图先使用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()

Tags: 函数inputraw键入if屏幕语句window
1条回答
网友
1楼 · 发布于 2024-04-26 14:07:09

函数raw_input( )在curses模式下不工作,getch()方法返回一个整数;它表示按键的ASCII代码。如果要从提示符扫描字符串,则将不起作用。您可以使用getstr函数:

window.getstr([y, x])

Read a string from the user, with primitive line editing capacity.

User Input

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)

我编写了如下的原始输入函数:

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()

输出:

enter image description here

相关问题 更多 >