【问题标题】:How to input a word in ncurses screen?如何在 ncurses 屏幕中输入单词?
【发布时间】:2014-02-14 16:33:36
【问题描述】:

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

【问题讨论】:

    标签: python ncurses


    【解决方案1】:

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

    window.getstr([y, x])

    从用户那里读取一个字符串,具有原始的行编辑能力。

    User Input

    还有一个检索整个字符串的方法,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函数如下:

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

    输出:

    【讨论】:

    • 两个问题。在“input = stdscr.getstr(r + 1, c, 20)”中为什么要从 r+1 读取?(因为 curosr 会自动移动到那里?) r+1 和 c 之后的“20”是什么意思?
    • @Mario (1) 我做了r + 1 将光标移动到下一行,(因为在? 之后 courser 会自动移动到下一行)
    • "20" 表示您可以输入 20 个字符的字符串。阅读我在答案中添加的所有 cmets 和文档
    猜你喜欢
    • 2021-08-15
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多