{Py3}如何让用户按下一个键并继续执行该程序而不按Enter键?

时间:2017-05-22 18:12:07

标签: python python-3.x input

    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(" ")

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

提前致谢!

〜洛伦佐

2 个答案:

答案 0 :(得分: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()

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

答案 1 :(得分:1)

你可以选择像:

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


Python有一个keyboard模块,具有许多功能。您可以在 Shell 控制台中使用它。 安装它,也许使用此命令:

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

您可以将其设置为多个密钥检测:

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的关键字 感谢。