gpt4 book ai didi

python - 在 pythoncurses 中使用退格键和 getch()

转载 作者:行者123 更新时间:2023-11-30 22:09:30 25 4
gpt4 key购买 nike

我希望用户能够输入每个字符,就像 getch() 的工作方式一样。我还打开了 echo() ,因为我想打印出用户输入的每个字符。但是,我还希望用户能够按退格键,并在按退格键之前按下的键从屏幕上删除,就像退格键在文本编辑器中的工作原理一样。我怎样才能做到这一点?我正在使用带有curses lib的python 3.6(显然)。如果您想查看到目前为止我的代码,这里是:

import curses

# ----- INIT -----
stdscr = curses.initscr()
curses.cbreak()
stdscr.keypad(1)

# ----- PRINT -----
text = "Hello world"
stdscr.addstr(1, 0, text + "\n")
stdscr.refresh()

# ----- MAIN LOOP ------
while 1:
c = stdscr.getch()
if c == ord('q'):
break

# ----- RESET TERMINAL -----
curses.echo()
curses.nocbreak()
stdscr.keypad(1)
curses.endwin()

最佳答案

您可以执行以下操作:禁用回显,使用显式库调用来回显除“退格”通常选择之外的字符:

import curses# ----- INIT -----stdscr = curses.initscr()curses.cbreak()curses.noecho()stdscr.keypad(1)# ----- PRINT -----text = "Hello world"stdscr.addstr(1, 0, text + "\n")stdscr.refresh()# ----- MAIN LOOP ------while 1:    c = stdscr.getch()    if c == ord('q'):        break    if c == 8 or c == 127 or c == curses.KEY_BACKSPACE:        stdscr.addstr("\b \b")    else:        stdscr.addch(c)# ----- RESET TERMINAL -----curses.echo()curses.nocbreak()stdscr.keypad(1)curses.endwin()

Pythoncurses 引用没有详细介绍 addch ,但由于它是诅咒的包装,您可以阅读它的 manual page关于文本退格 \b 被解释为使光标向后移动的方式。然后,该示例写入一个空格(删除其中的所有内容),然后将光标移回到空白处。

关于python - 在 pythoncurses 中使用退格键和 getch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51910946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com