无需按 Enter 即可在 Python 中获取单个字符作为输入(类似于 C++ 中的 getch)

首先,我是 Python 的新手,刚刚开始学习它。然而,我知道很多关于 C++ 的东西,我只是想在 Python 中实现其中的一些。


我已经对其进行了大量搜索,但找不到适合我要求的任何解决方案。请看下面的代码,


import os


class _Getch:

    """Gets a single character from standard input.  Does not echo to the

screen."""

    def __init__(self):

    try:

        self.impl = _GetchWindows()

    except:

        print("Error!")

    def __call__(self): return self.impl()


class _GetchWindows:

    def __init__(self):

        import msvcrt


    def __call__(self):

        import msvcrt

        return msvcrt.getch()




def mainfun():

    check = fh = True

    while check:

        fh = True

        arr = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

        print ("Welcome to Tic Tac Toe Game!!!\n\n")

        print("Enter 1 to Start Game")

        print("Enter 2 to Exit Game")

        a = _Getch()

        if a == "1":

            while fh:

                os.system("cls")

                drawboard()

                playermove()

                fh = checkresult()

        elif a == "2":

            break

       

如您所见,我在这里尝试做的是要求用户按 1 和 2 中的一个数字,然后将该数字存储在“a”中,然后将其用于我的要求。


现在,我首先尝试使用它,


    input('').split(" ")[0]

但这没有用。它要求我在输入 1 或 2 后始终按 Enter 键。所以,那是行不通的。


然后我找到了这个类的Getch,并实现了它。长话短说,它让我进入了一个永无止境的循环,现在我的结果是这样的,


Welcome to Tic Tac Toe Game!!!



Enter 1 to Start Game

Enter 2 to Exit Game


Press Enter to Continue....

Welcome to Tic Tac Toe Game!!!



Enter 1 to Start Game

Enter 2 to Exit Game


Press Enter to Continue....

Welcome to Tic Tac Toe Game!!!



Enter 1 to Start Game

Enter 2 to Exit Game


Press Enter to Continue....

这是一个永无止境的循环......即使我按下任何键,如“1”或“2”,它仍然不会停止并继续执行此操作并且不输入任何功能。


我想要的是类似这样的功能,

  1. 它应该在 PYCHARM 控制台上工作(我正在练习,我不想在终端上练习。我习惯使用我正在使用的 IDE 的控制台)

  2. 它暂停并等待用户输入任何输入(就像输入一样)

  3. 它接受用户输入的第一个密钥并将其存储到变量中。就像在这种情况下,如果用户按下“1”,那么它应该将该字符存储在“a”中,然后继续前进。您不必按“ENTER”继续。

  4. 如果用户按下任何其他按钮,如“a”或“b”或类似的任何东西,它不会做任何事情并继续要求输入,直到输入所需的数字“1”或“2”(我认为可以很容易地在这个 while 循环中处理)

换句话说,我只想在 Python 中替代 C++ 的 getch() 命令。我已经尝试了很多方法来找到它,但我找不到。请向我推荐一个问题,该问题提供了这个确切问题的解决方案或在此处提供解决方案。谢谢。



慕的地8271018
浏览 484回答 2
2回答

侃侃无极

看起来此功能不在标准 python 库中,但您可以重新创建它。首先,安装模块“键盘” $ pip3 install keyboard然后你可以使用 keyboard.is_pressed() 来查看是否按下了任何一个字符。import keyboard  # using module keyboardimport string # use this to get the alphabetprint("Input a character")def getch():    alphabet = list(string.ascii_lowercase)    while True:        for letter in alphabet: # detect when a letter is pressed            if keyboard.is_pressed(letter):                return letter        for num in range(10): # detect numbers 0-9            if keyboard.is_pressed(str(num)):                return str(num)answer = getch()print("you choose " + answer)编辑:对于 unix,您需要使用 sudo 运行脚本。此代码在 Windows 上应该可以正常工作。

汪汪一只猫

对于 EDIT-2:使用以下代码刷新屏幕:sys.stdout.flush()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python