gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:16:05 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于Python 读取修饰键(CTRL、ALT、SHIFT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48371780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com