【问题标题】:Python read modifier keys (CTRL, ALT, SHIFT)Python 读取修饰键(CTRL、ALT、SHIFT)
【发布时间】:2018-06-30 12:08:06
【问题描述】:

这在 Python 中似乎很难..

我正在尝试使用修饰键 CTRL、ALT 和 SHIFT 读取击键和组合。

我使用的是 Python 2.7。 它只需要在 Linux 上工作,但没有 X

目前,我只能使用 sys.stdin.read() 读取击键,但 stdin.read() 就像文件一样工作,不会返回修饰符..

def getch():
    """getch() -> key character

    Read a single keypress from stdin and return the resulting character. 
    Nothing is echoed to the console. This call will block if a keypress 
    is not already available, but will not wait for Enter to be pressed. 

    If the pressed key was a modifier key, nothing will be detected; if
    it were a special function key, it may return the first character of
    of an escape sequence, leaving additional characters in the buffer.
    """
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(fd)
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

函数返回击键组合的方式很灵活。首先想到的可能是返回一个包含组合的列表或字典。但主要问题是,如何检测它?!

【问题讨论】:

    标签: python python-2.7 keyboard stdin


    【解决方案1】:

    Stdin,根据定义是表示控制代码和字符的字节流。它不是关键事件流。要获取密钥,您需要使用特定于操作系统的功能。在 Linux 上,curses 窗口对象有一个getch 方法。 (另一个模块中有适用于 Windows 的内容。)

    Tk 及其 Python 的 tkinter 包装器使用特定于操作系统的方法让一个绑定到按键按下和释放事件,其中包括您提到的修饰符,在大多数不是特定于操作系统的代码中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 2015-01-23
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多