【问题标题】:{Py3} How do I get a user to press a key and carry on the program without pressing enter after?{Py3}如何让用户在不按回车的情况下按下一个键并继续程序?
【发布时间】:2017-10-22 12:01:55
【问题描述】:
    from time import sleep
    alive = True
    while alive == True:
        print("You have awoken in a unknown land.")
        sleep(2)
        print("\nDo you go north, south, east or west?")
        print("Press the up arrow to go north.")
        print("Press the down arrow to go south.")
        print("Press the left arrow to go west.")
        print("Press the right arrow to go east.")
        input(" ")

如何让用户按下其中一个箭头键并让程序继续运行而不需要按 Enter 键?

提前致谢!

~洛伦佐

【问题讨论】:

  • 哪个操作系统? msvcrt.getch 可用,但仅在 Windows 上可用。
  • 这可能比你想象的要复杂。例如,您可以看到here。从您的示例代码来看,您会发现通过接受“N、E、S、W”作为输入更容易推进您的项目。
  • 谢谢凯文,但我想让它对电脑世界的新手更友好一点,找到箭头比 N、E、S 和 W 键容易得多。不过只是个人喜好。 :)
  • 凯文没有建议,我建议。为了简单起见,我建议您暂时使用这些字母。我假设您正在学习 Python(while alive == True: 只是 while alive: 而您的 input 可能不会做任何事情,因为它没有分配给任何东西)。我认为你会更容易(目前)继续前进,而无需为此苦苦挣扎。

标签: python python-3.x input


【解决方案1】:

您可以查看pynput 之类的软件包以获得多平台支持。 Pynput 实现鼠标和键盘监听器。这也将允许您在类似 RPG 的游戏中进行 WSAD 移动。

对于键盘监听器,您可以使用 onpress/onrelease 键。帮助文件会有一些更好的例子。

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

如果您想使用上/下/左/右(箭头键)进行移动,这也可能是最简单、最痛苦的解决方案。

【讨论】:

  • 这看起来像个主意,谢谢你,会检查一下! :D 老实说,像 Python 这样的高级语言没有内置这个功能似乎非常愚蠢。
【解决方案2】:

你可以做出如下选择:

option = input('1/2/3/4:')

或:
Python 有一个具有许多特性的keyboard 模块。您可以在 ShellConsole 中使用它。 安装它,也许用这个命令:

pip3 install keyboard

然后在如下代码中使用它:

import keyboard #Using module keyboard
while True:  #making a loop
    try:  #used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('up'): #if key 'up' is pressed.You can use right,left,up,down and others
            print('You Pressed A Key!')
            #your code to move up here.
            break #finishing the loop
        else:
            pass
    except:
        break  #if user pressed other than the given key the loop will break

可以设置为多个Key Detection:

if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
    #then do this

你也可以这样做:

if keyboard.is_pressed('up') and keyboard.is_pressed('down'):
    #then do this

它还可以检测整个 Windows 的密钥。
谢谢。

【讨论】:

    猜你喜欢
    • 2015-01-23
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多