在Python中一次读取和打印一个字符getche()和backspace

2024-09-22 16:30:41 发布

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

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

我试过使用来自this module的getche,但它不能很好地处理backspaces。当我按backspace时,它会打印^?到控制台,我希望它删除字符。你知道吗


Tags: 函数用户this字符计划modulebackspacebackspaces
2条回答

docs非常清楚。你知道吗

tried using getche

不要这样做,因为getche()被记录为有你说你不想要的行为。你知道吗

打电话给getch(),并根据您的要求负责“回音”或维护显示器。你知道吗

例如,此代码实现了您想要的:

from getch import getch


def pr(s):
    print(s, end='', flush=True)


def get_word():
    DELETE = 127  # ASCII code
    word = ''
    c = ''
    while not c.isspace():
        c = getch()
        if ord(c) == DELETE:
            pr('\r' + ' ' * len(word) + '\r')
            word = word[:-1]
            pr(word)
        if c.isprintable():
            word += c
            pr(c)
    print('\n')
    return word

官方的定义是:

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

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

相关问题 更多 >