Python读取修饰键(CTRL,ALT,SHIFT)

时间:2018-01-21 21:14:18

标签: python python-2.7 keyboard stdin

这在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

我对函数返回击键组合的方式很灵活。我想到的第一件事就是返回一个列表或一个带有组合的字典。但主要的问题是,如何检测它?!

1 个答案:

答案 0 :(得分:2)

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

Tk和Python的tkinter包装器使用特定于操作系统的方法让一个绑定到按键和释放事件,包括你提到的修饰符,代码大部分都不是特定于操作系统的。