gpt4 book ai didi

python - 一次读取和打印一个字符 - Python 中的 getche() 和退格键

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:34 24 4
gpt4 key购买 nike

我想创建打字训练计划。我需要一个函数,它可以立即读取和打印用户点击的每个字符——类似于 getche()

我尝试使用 this module 中的 getche但它不能很好地处理退格。当我按下退格键时,它会打印 ^?到控制台,我希望它删除字符。

最佳答案

来自官方curses documentation page它的定义是:

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.

你说你想写一个打字训练程序,我认为最好的解决方案是使用 curses 库来完成这样的任务。

在 UNIX 系统上,它默认安装了 python,如果你的目标是 Windows 系统,我发现了 windows-curses大大增加支持。

基本上,您可以在this 中找到HOWTO 指南。来自官方文档的页面。

这是创建文本框小部件的示例用法

curses.textpad模块应该对您非常有用。

import curses
from curses import wrapper
from curses.textpad import Textbox, rectangle

def main(stdscr):
stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)")

editwin = curses.newwin(5,30, 2,1)
rectangle(stdscr, 1,0, 1+5+1, 1+30+1)
stdscr.refresh()

box = Textbox(editwin)

# Let the user edit until Ctrl-G is struck.
box.edit()

# Get resulting contents
message = box.gather()
print(message)

if __name__ == '__main__':
wrapper(main)

这是使用 windows-curses 模块的样子

Curses example screenshot

你可以使用这个库做很多事情,我建议你继续阅读我提供的链接上的文档。

关于python - 一次读取和打印一个字符 - Python 中的 getche() 和退格键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56906256/

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