翻译python keyboard模块的说明文档

发布时间 2023-08-25 20:05:53作者: 顺其自然,道法自然

之前有介绍过全局热键keyboard库, 简略介绍了它的使用. 为全面了解, 我把其说明文档翻译了一下, 如下(中英文对照):

This project is currently unmaintained. It works for many cases, and I wish to pick it up again in the future, but you might encounter some friction and limited features using it.
这个项目目前处于无人维护的状态。它在许多情况下可以工作,我希望在未来可以再次维护它,但是在使用的时候你可能会遇到一些问题和功能上的限制。



keyboard

Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.
使用这个小型的Python库可以完全控制你的键盘。挂钩全局事件,注册热键,模拟按键等等,你能做的多得多。

Features 特性

  • Global event hook on all keyboards (captures keys regardless of focus).
    全局事件钩子,适用于所有键盘(可以捕获按键事件,无论焦点在哪里)。
  • Listen and send keyboard events.
    监听和发送键盘事件。
  • Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!).
    可在Windows和Linux(需要sudo权限)系统下使用,并实验性地支持OS X(感谢 @glitchassassin!)。
  • Pure Python, no C modules to be compiled.
    使用纯Python编写,无需编译C模块。
  • Zero dependencies. Trivial to install and deploy, just copy the files.
    零依赖。安装和部署非常简单,直接复制文件即可。
  • Python 2 and 3.
    支持Python 2和3。
  • Complex hotkey support (e.g. ctrl+shift+m, ctrl+space) with controllable timeout.
    支持复杂的快捷键(例如ctrl+shift+m, ctrl+space)并可控制超时时间。
  • Includes high level API (e.g. record and play, add_abbreviation).
    包含高级API(例如recordplay,add_abbreviation)。
  • Maps keys as they actually are in your layout, with full internationalization support (e.g. Ctrl+ç).
    映射键盘布局上键位的实际按键,具有完整的国际化支持(例如 Ctrl+ç)。
  • Events automatically captured in separate thread, doesn't block main program.
    事件自动捕获在单独的线程中,不会阻塞主程序。
  • Tested and documented.
    测试并文档化。
  • Doesn't break accented dead keys (I'm looking at you, pyHook).
    不会破坏带有重音的死键(我在看你,pyHook)。什么意思, 不懂啊.
  • Mouse support available via project mouse (pip install mouse).
    支持鼠标操作(参见项目 mouse (pip install mouse)。

Usage 用法

Install the PyPI package:
安装PyPI包:

pip install keyboard

or clone the repository (no installation required, source files are sufficient):
或者克隆仓库(不需要安装,源码文件就可以使用):

git clone https://github.com/boppreh/keyboard

or download and extract the zip into your project folder.
或者下载并解压zip到项目文件夹.

Then check the API docs below to see what features are available.
然后查看API文档查看可用功能.

Example 示例

Use as library:
作为库使用:

import keyboard

keyboard.press_and_release('shift+s, space')

keyboard.write('The quick brown fox jumps over the lazy dog.')

keyboard.add_hotkey('ctrl+shift+a', print, args=('triggered', 'hotkey'))

# Press PAGE UP then PAGE DOWN to type "foobar".
# 先按 Page Up 然后按 Page Down 来输入"foobar"。
keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))

# Blocks until you press esc.
# 阻塞直到你按下 esc
keyboard.wait('esc')

# Record events until 'esc' is pressed.
# 记录直到 'esc' 被按下。
recorded = keyboard.record(until='esc')
# Then replay back at three times the speed.
# 然后以三倍速度回放.
keyboard.play(recorded, speed_factor=3)

# Type @@ then press space to replace with abbreviation.
# 先输入 @@ 然后按空格来替换为缩写.
keyboard.add_abbreviation('@@', 'my.long.email@example.com')

# Block forever, like `while True`.
# 阻塞,就像 `while True`
keyboard.wait()

Use as standalone module:
作为独立模块使用:

# Save JSON events to a file until interrupted:  
# 以JSON格式保存事件到文件直到被中断:
python -m keyboard > events.txt

cat events.txt
# {"event_type": "down", "scan_code": 25, "name": "p", "time": 1622447562.2994788, "is_keypad": false}
# {"event_type": "up", "scan_code": 25, "name": "p", "time": 1622447562.431007, "is_keypad": false}
# ...

# Replay events
# 回放事件
python -m keyboard < events.txt

Known limitations 已知限制:

  • Events generated under Windows don't report device id (event.device == None). #21
    在Windows下生成的事件不会报告设备id(event.device == None)。
  • Media keys on Linux may appear nameless (scan-code only) or not at all. #20
    在Linux下媒体键可能没有名字(只有扫描码)或者根本就没有。
  • Key suppression/blocking only available on Windows. #22
    键盘抑制/阻止功能只在Windows系统上可用。
  • To avoid depending on X, the Linux parts reads raw device files (/dev/input/input*) but this requires root.
    为了避免依赖X,Linux部分读取原始设备文件(/dev/input/input*),但需要root。
  • Other applications, such as some games, may register hooks that swallow all key events. In this case keyboard will be unable to report events.
    其他应用程序,如游戏,可能会注册钩子,吞下所有键事件。在这种情况下,keyboard将无法报告事件。
  • This program makes no attempt to hide itself, so don't use it for keyloggers or online gaming bots. Be responsible.
    本程序不会尝试隐藏自己,因此不要使用它进行键盘记录器或在线游戏机器人。责任自负。
  • SSH connections forward only the text typed, not keyboard events. Therefore if you connect to a server or Raspberry PI that is running keyboard via SSH, the server will not detect your key events.
    SSH连接只转发输入的文本,而不是键盘事件. 因此,如果你通过SSH连接到运行着keyboard的服务器或树莓派,服务器端将无法检测到你的键盘输入。

Common patterns and mistakes 常见的模式和错误

Preventing the program from closing 阻止程序关闭

import keyboard
keyboard.add_hotkey('space', lambda: print('space was pressed!'))
# If the program finishes, the hotkey is not in effect anymore.  
# 如果程序结束了,热键就不再生效了。

# Don't do this! This will use 100% of your CPU.
# 不要使用下面的代码, 它会占用100%的CPU。
#while True: pass

# Use this instead
# 使用下面的代码
keyboard.wait()

# or this
# 或者使用下面的代码
import time
while True:
    time.sleep(1000000)

Waiting for a key press one time 等待某个键

import keyboard

# Don't do this! This will use 100% of your CPU until you press the key.
# 不要使用下面的代码, 它会占用100%的CPU
#
#while not keyboard.is_pressed('space'):
#    continue
#print('space was pressed, continuing...')

# Do this instead
# 改成下面的代码
keyboard.wait('space')
print('space was pressed, continuing...')

Repeatedly waiting for a key press 重复等待某个键

import keyboard

# Don't do this!
#
#while True:
#    if keyboard.is_pressed('space'):
#        print('space was pressed!')
#
# This will use 100% of your CPU and print the message many times.

# Do this instead
while True:
    keyboard.wait('space')
    print('space was pressed! Waiting on it again...')

# or this
keyboard.add_hotkey('space', lambda: print('space was pressed!'))
keyboard.wait()

Invoking code when an event happens 按某键触发代码

import keyboard

# Don't do this! This will call `print('space')` immediately then fail when the key is actually pressed.
#keyboard.add_hotkey('space', print('space was pressed'))

# Do this instead
keyboard.add_hotkey('space', lambda: print('space was pressed'))

# or this
def on_space():
    print('space was pressed')
keyboard.add_hotkey('space', on_space)

# or this
while True:
    # Wait for the next event.
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN and event.name == 'space':
        print('space was pressed')

'Press any key to continue' 按任意键继续

# Don't do this! The `keyboard` module is meant for global events, even when your program is not in focus.  
# 不要这样做!keyboard 模块是用于全局事件的,即使你的程序不在焦点中。
#import keyboard
#print('Press any key to continue...')
#keyboard.get_event()

# Do this instead
input('Press enter to continue...')

# Or one of the suggestions from here
# https://stackoverflow.com/questions/983354/how-to-make-a-script-wait-for-a-pressed-key

API

Table of Contents 主要内容

keyboard.KEY_DOWN

= 'down'

keyboard.KEY_UP

= 'up'

class keyboard.KeyboardEvent

KeyboardEvent.device

KeyboardEvent.event_type

KeyboardEvent.is_keypad

KeyboardEvent.modifiers

KeyboardEvent.name

KeyboardEvent.scan_code

KeyboardEvent.time

KeyboardEvent.to_json(self, ensure_ascii=False)

[source]

keyboard.all_modifiers

= {'alt', 'alt gr', 'ctrl', 'left alt', 'left ctrl', 'left shift', 'left windows', 'right alt', 'right ctrl', 'right shift', 'right windows', 'shift', 'windows'}

keyboard.sided_modifiers

= {'alt', 'ctrl', 'shift', 'windows'}

keyboard.version

= '0.13.5'

keyboard.is_modifier(key)

[source]

Returns True if key is a scan code or name of a modifier key.
如果key是一个修改键的扫描码或者名称,则返回True。

keyboard.key_to_scan_codes(key, error_if_missing=True)

[source]

Returns a list of scan codes associated with this key (name or scan code).
返回与该键(名称或扫描码)关联的扫描码列表。

keyboard.parse_hotkey(hotkey)

[source]

Parses a user-provided hotkey into nested tuples representing the
parsed structure, with the bottom values being lists of scan codes.
Also accepts raw scan codes, which are then wrapped in the required
number of nestings.
将用户提供的热键解析为表示解析结构的嵌套元组,底层的值是扫描码的列表。也接受原始扫描码,然后将其包装在所需数量的嵌套中。
Example:


parse_hotkey("alt+shift+a, alt+b, c")
#    Keys:    ^~^ ^~~~^ ^  ^~^ ^  ^
#    Steps:   ^~~~~~~~~~^  ^~~~^  ^

# ((alt_codes, shift_codes, a_codes), (alt_codes, b_codes), (c_codes,))

keyboard.send(hotkey, do_press=True, do_release=True)

[source]

Sends OS events that perform the given hotkey hotkey.
发送执行给定热键的操作系统事件。

  • hotkey can be either a scan code (e.g. 57 for space), single key
    (e.g. 'space') or multi-key, multi-step hotkey (e.g. 'alt+F4, enter').
    hotkey可以是一个扫描码(例如空格键为57),单个键(例如'space')或多键多步热键(例如'alt+F4, enter')。
  • do_press if true then press events are sent. Defaults to True.
    如果为true,则会发送按下事件。默认为True。
  • do_release if true then release events are sent. Defaults to True.
    如果为true,则会发送释放事件。默认为True。
send(57)
send('ctrl+alt+del')
send('alt+F4, enter')
send('shift+s')

Note: keys are released in the opposite order they were pressed.
注意:键的释放顺序与按下顺序相反。

keyboard.press(hotkey)

[source]

Presses and holds down a hotkey (see send).
按下并持续按住一个热键(见 send)。

keyboard.release(hotkey)

[source]

Releases a hotkey (see send).
释放一个热键(见 send)。

keyboard.is_pressed(hotkey)

[source]

Returns True if the key is pressed.


is_pressed(57) #-> True
is_pressed('space') #-> True
is_pressed('ctrl+space') #-> True

keyboard.call_later(fn, args=(), delay=0.001)

[source]

Calls the provided function in a new thread after waiting some time.
Useful for giving the system some time to process an event, without blocking
the current execution flow.
在等待一段时间后,在新线程中调用提供的函数。用于在不阻塞当前执行流的情况下给系统一些时间来处理事件。

keyboard.hook(callback, suppress=False, on_remove=<lambda>)

[source]

Installs a global listener on all available keyboards, invoking callback
each time a key is pressed or released.
在所有可用键盘上安装全局监听器,每当按下或释放一个键时调用回调函数。

The event passed to the callback is of type keyboard.KeyboardEvent,
with the following attributes:
传递给回调的事件是keyboard.KeyboardEvent类型,具有以下属性:

  • name: an Unicode representation of the character (e.g. "&") or
    description (e.g. "space"). The name is always lower-case.
    name:字符(例如"&")或描述(例如"space")的Unicode表示。名称总是小写。
  • scan_code: number representing the physical key, e.g. 55.
    scan_code:表示物理键的数字,例如55。
  • time: timestamp of the time the event occurred, with as much precision
    as given by the OS.
    time:事件发生时的时间戳,精度由操作系统给出。

Returns the given callback for easier development.
返回给定的回调以方便开发。

keyboard.on_press(callback, suppress=False)

[source]

Invokes callback for every KEY_DOWN event. For details see hook.

对每个 KEY_DOWN 事件调用回调函数。详情见 hook。

keyboard.on_release(callback, suppress=False)

[source]

Invokes callback for every KEY_UP event. For details see hook.

对每个 KEY_UP 事件调用回调函数。详情见 hook。

keyboard.hook_key(key, callback, suppress=False)

[source]

Hooks key up and key down events for a single key. Returns the event handler
created. To remove a hooked key use unhook_key(key) or
unhook_key(handler).
为单个键钩取按下和释放事件。返回创建的事件处理程序。要取消键钩使用 unhook_key(key) 或 unhook_key(handler)。

Note: this function shares state with hotkeys, so clear_all_hotkeys
affects it as well.
注意:此函数与热键共享状态,所以 clear_all_hotkeys 也会影响它。

keyboard.on_press_key(key, callback, suppress=False)

[source]

Invokes callback for KEY_DOWN event related to the given key. For details see hook.

keyboard.on_release_key(key, callback, suppress=False)

[source]

Invokes callback for KEY_UP event related to the given key. For details see hook.

keyboard.unhook(remove)

[source]

Removes a previously added hook, either by callback or by the return value
of hook.
删除先前添加的钩子,可以通过回调或钩子的返回值。

keyboard.unhook_all()

[source]

Removes all keyboard hooks in use, including hotkeys, abbreviations, word
listeners, recorders and waits.
删除所有正在使用的键盘钩子,包括热键、缩写、单词监听器、record 和 wait。

keyboard.block_key(key)

[source]

Suppresses all key events of the given key, regardless of modifiers.
禁用给定键的所有按键事件,无论它有哪些修饰符。

keyboard.remap_key(src, dst)

[source]

Whenever the key src is pressed or released, regardless of modifiers,
press or release the hotkey dst instead.
每当按下或释放键src时,无论它有哪些修饰符,都按下或释放热键dst来代替。

keyboard.parse_hotkey_combinations(hotkey)

[source]

Parses a user-provided hotkey. Differently from parse_hotkey,
instead of each step being a list of the different scan codes for each key,
each step is a list of all possible combinations of those scan codes.
解析用户提供的热键。与parse_hotkey不同的是,每一步不是每个键的不同扫描码的列表,而是这些扫描码的所有可能组合的列表。

keyboard.add_hotkey(hotkey, callback, args=(), suppress=False, timeout=1, trigger_on_release=False)

[source]

Invokes a callback every time a hotkey is pressed. The hotkey must
be in the format ctrl+shift+a, s. This would trigger when the user holds
ctrl, shift and "a" at once, releases, and then presses "s". To represent
literal commas, pluses, and spaces, use their names ('comma', 'plus',
'space').
每次按下热键时调用回调。热键格式必须是 ctrl+shift+a, s。这将在用户同时按住ctrl、shift和“a”,释放,然后按“s”时触发。要表示逗号、加号和空格,请使用它们的名称('comma'、'plus'、'space')。

  • args is an optional list of arguments to passed to the callback during
    each invocation.
    args 是在每次调用时传递给回调的可选参数列表。
  • suppress defines if successful triggers should block the keys from being
    sent to other programs.
    定义是否应阻止触发的键发送到其他程序。
  • timeout is the amount of seconds allowed to pass between key presses.
    是按键之间允许通过的秒数。
  • trigger_on_release if true, the callback is invoked on key release instead
    of key press. 如果为true,则在释放键而不是按下键时调用回调。

The event handler function is returned. To remove a hotkey call
remove_hotkey(hotkey) or remove_hotkey(handler).
before the hotkey state is reset.
返回事件处理函数。要删除热键,在热键状态重置前调用remove_hotkey(hotkey)或remove_hotkey(handler)。

Note: hotkeys are activated when the last key is pressed, not released.
Note: the callback is executed in a separate thread, asynchronously. For an
example of how to use a callback synchronously, see wait.
注意:热键在按下最后一个键,而不是释放时激活。
注意:回调在单独的线程中异步执行。有关如何同步使用回调的示例,请参见wait。

Examples:


# Different but equivalent ways to listen for a spacebar key press.  
# 不同但等效的方法来侦听空格键按下。
add_hotkey(' ', print, args=['space was pressed'])
add_hotkey('space', print, args=['space was pressed'])
add_hotkey('Space', print, args=['space was pressed'])
# Here 57 represents the keyboard code for spacebar; so you will be pressing 'spacebar', not '57' to activate the print function.  
# 这里57表示空格键的键盘码,所以你将会按'空格键',而不是'57'来激活print函数。
add_hotkey(57, print, args=['space was pressed'])

add_hotkey('ctrl+q', quit)
add_hotkey('ctrl+alt+enter, space', some_callback)

keyboard.remove_hotkey(hotkey_or_callback)

[source]

Removes a previously hooked hotkey. Must be called with the value returned
by add_hotkey.

keyboard.unhook_all_hotkeys()

[source]

Removes all keyboard hotkeys in use, including abbreviations, word listeners,
recorders and waits.

keyboard.remap_hotkey(src, dst, suppress=True, trigger_on_release=False)

[source]

Whenever the hotkey src is pressed, suppress it and send
dst instead.

Example:


remap('alt+w', 'ctrl+up')

keyboard.stash_state()

[source]

Builds a list of all currently pressed scan codes, releases them and returns
the list. Pairs well with restore_state and restore_modifiers.
构建一个当前所有被按下的扫描码的列表,释放它们并返回该列表。与restore_state和restore_modifiers配合使用效果很好。

keyboard.restore_state(scan_codes)

[source]

Given a list of scan_codes ensures these keys, and only these keys, are
pressed. Pairs well with stash_state, alternative to restore_modifiers.

给定一个扫描码列表,确保只按下这些键。与stash_state搭配使用效果很好,可替代restore_modifiers。

keyboard.restore_modifiers(scan_codes)

[source]

Like restore_state, but only restores modifier keys.

keyboard.write(text, delay=0, restore_state_after=True, exact=None)

[source]

Sends artificial keyboard events to the OS, simulating the typing of a given
text. Characters not available on the keyboard are typed as explicit unicode
characters using OS-specific functionality, such as alt+codepoint.
向操作系统发送伪造的键盘事件,模拟输入给定文本。键盘上不存在的字符会以操作系统特定的方式输入明确的unicode字符,比如alt+codepoint。

To ensure text integrity, all currently pressed keys are released before
the text is typed, and modifiers are restored afterwards.
为确保文本的完整性,在输入文本之前会释放所有当前按下的键,之后恢复修饰键。

  • delay is the number of seconds to wait between keypresses, defaults to
    no delay.
    是按键之间的等待秒数,默认没有延迟
  • restore_state_after can be used to restore the state of pressed keys
    after the text is typed, i.e. presses the keys that were released at the
    beginning. Defaults to True.
    可用于在输入文本之后恢复按键状态,即按下开始时释放的键。默认为True。
  • exact forces typing all characters as explicit unicode (e.g.
    alt+codepoint or special events). If None, uses platform-specific suggested
    value.
    强制所有字符以明确的unicode输入(例如alt+codepoint或特殊事件)。如果为None,使用平台建议的值。

keyboard.wait(hotkey=None, suppress=False, trigger_on_release=False)

[source]

Blocks the program execution until the given hotkey is pressed or,
if given no parameters, blocks forever.
阻塞程序执行,直到按下给定的热键,如果不给定参数,则永久阻塞。

keyboard.get_hotkey_name(names=None)

[source]

Returns a string representation of hotkey from the given key names, or
the currently pressed keys if not given. This function:
从给定的键名返回热键的字符串表示,如果未给定则返回当前按下的键。该函数:

  • normalizes names;
    规范化名称
  • removes "left" and "right" prefixes;
    移除"left"和"right"前缀;
  • replaces the "+" key name with "plus" to avoid ambiguity;
    用"plus"替换键名"+",以避免歧义;
  • puts modifier keys first, in a standardized order;
    首先放修饰键,按标准顺序;
  • sort remaining keys;
    对其余键排序;
  • finally, joins everything with "+".
    最后用"+"连接起来。

Example:


get_hotkey_name(['+', 'left ctrl', 'shift'])
# "ctrl+shift+plus"

keyboard.read_event(suppress=False)

[source]

Blocks until a keyboard event happens, then returns that event.

keyboard.read_key(suppress=False)

[source]

Blocks until a keyboard event happens, then returns that event's name or,
if missing, its scan code.

keyboard.read_hotkey(suppress=True)

[source]

Similar to read_key(), but blocks until the user presses and releases a
hotkey (or single key), then returns a string representing the hotkey
pressed.

Example:


read_hotkey()
# "ctrl+shift+p"

keyboard.get_typed_strings(events, allow_backspace=True)

[source]

Given a sequence of events, tries to deduce what strings were typed.
Strings are separated when a non-textual key is pressed (such as tab or
enter). Characters are converted to uppercase according to shift and
capslock status. If allow_backspace is True, backspaces remove the last
character typed.
给定一系列事件,试图推断输入了什么字符串。当按下非文本键(如tab或enter)时分隔字符串。根据shift和caps lock状态将字符转换为大写。如果allow_backspace为True,backspace会删除最后输入的字符。

This function is a generator, so you can pass an infinite stream of events
and convert them to strings in real time.
此函数是一个生成器,所以你可以传递无限的事件流并实时转换为字符串。

Note this functions is merely an heuristic. Windows for example keeps per-
process keyboard state such as keyboard layout, and this information is not
available for our hooks.
注意这只是一个启发式函数。例如Windows为每个进程保留键盘状态比如布局,钩子无法获取这些信息。


get_type_strings(record()) #-> ['This is what', 'I recorded', '']

keyboard.start_recording(recorded_events_queue=None)

[source]

Starts recording all keyboard events into a global variable, or the given
queue if any. Returns the queue of events and the hooked function.
开始录制所有键盘事件到一个全局变量中,或者给定的队列中(如果有的话)。返回事件队列和钩子函数。

Use stop_recording() or unhook(hooked_function) to stop.

keyboard.stop_recording()

[source]

Stops the global recording of events and returns a list of the events
captured.

keyboard.record(until='escape', suppress=False, trigger_on_release=False)

[source]

Records all keyboard events from all keyboards until the user presses the
given hotkey. Then returns the list of events recorded, of type
keyboard.KeyboardEvent. Pairs well with
play(events).
录制所有键盘的所有键盘事件,直到用户按下给定的热键。然后返回记录的 KeyboardEvent 类型事件列表。与 play(events) 配合使用效果好。

Note: this is a blocking function.
注意:这是一个阻塞函数。
Note: for more details on the keyboard hook and events see hook.
注意:有关键盘钩子和事件的更多详细信息,请参阅 hook。

keyboard.play(events, speed_factor=1.0)

[source]

Plays a sequence of recorded events, maintaining the relative time
intervals. If speed_factor is <= 0 then the actions are replayed as fast
as the OS allows. Pairs well with record().
播放一系列记录的事件,保持相对时间间隔。如果speed_factor <= 0,则会尽可能快地重播动作。与record()搭配使用效果好。

Note: the current keyboard state is cleared at the beginning and restored at
the end of the function.
注意: 当前键盘状态会在函数开始时清除,在结束时恢复。

keyboard.add_word_listener(word, callback, triggers=['space'], match_suffix=False, timeout=2)

[source]

Invokes a callback every time a sequence of characters is typed (e.g. 'pet')
and followed by a trigger key (e.g. space). Modifiers (e.g. alt, ctrl,
shift) are ignored.
每次键入一串字符(例如'pet')并以触发键结束时(例如空格),调用回调函数。忽略修饰键(例如alt、ctrl、shift)。

  • word the typed text to be matched. E.g. 'pet'.
    是要匹配的文本,例如'pet'。
  • callback is an argument-less function to be invoked each time the word
    is typed.
    是匹配时要调用的无参数函数。
  • triggers is the list of keys that will cause a match to be checked. If
    the user presses some key that is not a character (len>1) and not in
    triggers, the characters so far will be discarded. By default the trigger
    is only space.
    是会触发匹配检查的按键列表。如果用户按下的键不是字符(len>1)且不在triggers中,则目前键入的字符会被丢弃。默认触发键只有空格。
  • match_suffix defines if endings of words should also be checked instead
    of only whole words. E.g. if true, typing 'carpet'+space will trigger the
    listener for 'pet'. Defaults to false, only whole words are checked.
    定义在检查完整单词时,是否也检查词尾。例如设为true时,键入'carpet'+空格会触发'pet'的监听器。默认为false,只检查完整单词。
  • timeout is the maximum number of seconds between typed characters before
    the current word is discarded. Defaults to 2 seconds.
    是键入字符之间超时秒数,超时当前词会被丢弃。默认2秒。

Returns the event handler created. To remove a word listener use
remove_word_listener(word) or remove_word_listener(handler).
返回创建的事件处理程序。要删除单词监听器可用 remove_word_listener(word) 或 remove_word_listener(handler)。

Note: all actions are performed on key down. Key up events are ignored.
注意:所有动作在按下时执行。忽略按键抬起事件。
Note: word matches are case sensitive.
注意:单词匹配是区分大小写的。

keyboard.remove_word_listener(word_or_handler)

[source]

Removes a previously registered word listener. Accepts either the word used
during registration (exact string) or the event handler returned by the
add_word_listener or add_abbreviation functions.

keyboard.add_abbreviation(source_text, replacement_text, match_suffix=False, timeout=2)

[source]

Registers a hotkey that replaces one typed text with another. For example
注册一个热键,将输入的文本替换为另一个文本。例如


add_abbreviation('tm', u'™')

Replaces every "tm" followed by a space with a ™ symbol (and no space). The
replacement is done by sending backspace events.
用TM符号(不带空格)替换每个后跟空格的“tm”。替换通过发送退格事件完成。

  • match_suffix defines if endings of words should also be checked instead
    of only whole words. E.g. if true, typing 'carpet'+space will trigger the
    listener for 'pet'. Defaults to false, only whole words are checked.
    定义是否也检查词尾,而不只是完整单词。例如设为true时,输入“carpet”+空格也会触发“pet”的监听。默认为false,只检查完整单词。

  • timeout is the maximum number of seconds between typed characters before
    the current word is discarded. Defaults to 2 seconds.
    是键入字符之间的最大秒数,超时当前词会被丢弃。默认为2秒。

For more details see add_word_listener.

keyboard.normalize_name(name)

[source]

Given a key name (e.g. "LEFT CONTROL"), clean up the string and convert to
the canonical representation (e.g. "left ctrl") if one is known.
给定一个键名(例如“LEFT CONTROL”),清理字符串并转换为已知的标准表示(例如“left ctrl”)。