如何在使用键盘模块时清除输入?

2024-04-24 07:52:52 发布

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

我正在用Python和库keyboard编写一个基于文本的游戏。 在代码的某一点上,我必须收集一个通过以下代码得到的数字:

if menu == "test":
    try:
        x = int(input("Enter a Number: "))
    except ValueError:
        print("Please input integer only...")

但要将菜单设置为“测试”,我必须使用键盘键入2 1。 我的问题是,虽然菜单不是“测试”,但输入已经被收集。 运行代码时,我得到以下信息:

Enter a Number: 211

我可以很容易地在命令提示符下删除211,然后键入一些内容 但我希望它自动删除自己,这样我就可以:

Enter a Number:

我已经尝试过的:

input().clear()

input(None)

x = 0

#import os   --at the beginning of the code

os.system("clear")

Tags: the代码文本游戏numberinput键入if
2条回答

我认为我的目标有点不明确,所以我还编写了在已经显示的部分(但简化)之前的代码

run = True
while run
   
    menu = "menu1"
    press1 = keyboard.is_pressed("1")
    press2 = keyboard.is_pressed("2")

    if menu == "menu1":
        #stuff
        if press2:                    # 2 is pressed
            menu = "menu2"

    if menu == "menu2":
        #stuff
        if press1:                    # 1 is pressed
            menu = "menu3"

    if menu == "menu3":
        #stuff
        if press1:                    # 1 is pressed
            menu = "menu4"

                                     
                                      # summed up you press 2 1 1 to get menu to "menu4"

    #now the code that was already in the question

    if menu == "menu4":
        try:
            x = int(input("Enter a Number: "))
        except ValueError:
            print("Please input integer only...")

menu4中的输入会记住我以前键入的所有内容(211) 但是我不想要它,输入已经是211了,不是什么都没有,因为我输入了211 但我不希望它是什么,当谈到菜单4它不是我试图知道我以前键入了什么

当我运行我想要的代码时,应该发生以下情况:

# menu = "menu1"
# programm does sth and waits for input
# user presses "2"
# menu = "menu2"
# programm does sth and waits for input
# user presses "1"
# menu = "menu3"
# programm does sth and waits for input
# user presses "1"
# menu = "menu4" 

# programm prints the following:

# Enter a Number:   < here is a EMPTY space where you can write sth.

# Please input integer only...           #(eventually)

这种情况不应发生:

# programm prints the following:

# Enter a Number: 211   < here it is NOT EMPTY

# Please input integer only...           #(eventually)

如果要避免在终端中显示输出,可以在MacOS和Linux上使用以下选项:

import sys
import tty
import termios

def hidden_input(*args):
    stdin = sys.stdin.fileno()
    tattr = termios.tcgetattr(stdin)
    try:
        tty.setcbreak(stdin, termios.TCSANOW)
        return input(*args)
    finally:
        termios.tcsetattr(stdin, termios.TCSANOW, tattr)

这是通过将TTY(终端仿真器99%的时间)设置为cbreak模式来实现的Which does请注意以下事项:

The traditional 'raw' mode is the easier one to explain; it does no in-kernel processing of input or output at all. All characters are returned immediately when typed and all output is produced as-is. The traditional 'cbreak' mode is used for things like password entry; it returns characters immediately as they're typed, doesn't echo characters, and doesn't do any in-kernel line editing (which mostly means that your program can actually see the various editing characters). At a high level, there are two major differences between 'cbreak' and 'raw'. First, cbreak leaves output handling unchanged, which may be relatively 'cooked'. Second, cbreak still allows you to interrupt the program with ^C, suspend it, and so on. You can see this in action with most programs (such as passwd, su, or sudo) that ask for a password; you can immediately interrupt them with ^C in a way that, eg, vi does not respond to.

The low-level settings for cbreak are:

  • disable ECHO; this stops typed characters from being echoed.
  • disable ICANON; this turns off line editing. set VMIN to 1 and VTIME to 0; this makes it so that a read() returns immediately once there's (at least) one character available.

请注意,因为readline仍在使用中,所以您仍然可以像正常情况一样编辑键入的行

在Windows上,我不知道如何轻松地做到这一点

如果要清除在用户按下enter键后键入的输入,这会有点困难,因为需要部分清除已打印的输出,这需要使用特殊的控制代码

针对Windows的一个可能更简单的解决方案:以下内容将清除MacOS和Linux上的整个终端,但也将在Windows Terminal中工作(与默认的cmd.exe不同!)

print('\x1b[2J')

您还可以尝试通过colorama包将其用于普通的Windows终端,正如martineau的评论中所建议的

相关问题 更多 >