【问题标题】:Python 3 pressed key detectPython 3 按键检测
【发布时间】:2019-11-28 08:44:46
【问题描述】:

是否有内置的支持方法来检测 Python 3 中按下了哪个键?没有第三方库?

我在 Google 中搜索过,大多数答案都使用外部库。有没有办法使用纯 python 做到这一点?

【问题讨论】:

标签: python keypress


【解决方案1】:

我得到了一些答案,我不知道所有导入的库是否都内置在 python 中,但它工作得很好

#!/usr/bin/python3

# adapted from https://github.com/recantha/EduKit3-RC-Keyboard/blob/master/rc_keyboard.py

import sys, termios, tty, os, time

def getch():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)

    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

button_delay = 0.2

while True:
    char = getch()

    if (char == "p"):
        print("Stop!")
        exit(0)

    if (char == "a"):
        print("Left pressed")
        time.sleep(button_delay)

    elif (char == "d"):
        print("Right pressed")
        time.sleep(button_delay)

    elif (char == "w"):
        print("Up pressed")
        time.sleep(button_delay)

    elif (char == "s"):
        print("Down pressed")
        time.sleep(button_delay)

    elif (char == "1"):
        print("Number 1 pressed")
        time.sleep(button_delay)

【讨论】:

猜你喜欢
  • 2014-04-17
  • 2013-08-17
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 2010-09-22
相关资源
最近更新 更多