python - 如何阻止在python中键入按键
问题描述
我正在开发一个为我重新映射计算机键盘的程序,因为我输入的是另一种键盘布局。但是,当按下一个键时,我能够发送不同的击键,但我无法阻止原始击键也被注册为输入。我正在使用 Python,任何帮助将不胜感激。
from pynput.keyboard import Key, KeyCode, Listener, Controller
# Your functions
keyboard = Controller()
def function_a():
keyboard.type('a')
def function_b():
keyboard.type('b')
def function_c():
keyboard.type('c')
def function_d():
keyboard.type('e')
# Create a mapping of keys to function (use frozenset as sets are not hashable - so they can't be used as keys)
combination_to_function = {
frozenset([KeyCode(char='a')]): function_a,
frozenset([KeyCode(char='b')]): function_b,
frozenset([KeyCode(char='c')]): function_c,
frozenset([KeyCode(char='d')]): function_d,
## frozenset([KeyCode(char='e')]): function_e,
## frozenset([KeyCode(char='f')]): function_f,
## frozenset([KeyCode(char='g')]): function_g,
## frozenset([KeyCode(char='h')]): function_h,
## frozenset([KeyCode(char='i')]): function_i,
## frozenset([KeyCode(char='j')]): function_j,
## frozenset([KeyCode(char='k')]): function_k,
## frozenset([KeyCode(char='l')]): function_l,
## frozenset([KeyCode(char='m')]): function_m,
## frozenset([KeyCode(char='n')]): function_n,
## frozenset([KeyCode(char='o')]): function_o,
## frozenset([KeyCode(char='p')]): function_p,
## frozenset([KeyCode(char='q')]): function_q,
## frozenset([KeyCode(char='r')]): function_r,
## frozenset([KeyCode(char='s')]): function_s,
## frozenset([KeyCode(char='t')]): function_t,
## frozenset([KeyCode(char='u')]): function_u,
## frozenset([KeyCode(char='v')]): function_v,
## frozenset([KeyCode(char='w')]): function_w,
## frozenset([KeyCode(char='x')]): function_x,
## frozenset([KeyCode(char='y')]): function_y,
## frozenset([KeyCode(char='z')]): function_z,
}
# Currently pressed keys
current_keys = set()
def on_press(key):
# When a key is pressed, add it to the set we are keeping track of and check if this set is in the dictionary
current_keys.add(key)
if frozenset(current_keys) in combination_to_function:
# If the current set of keys are in the mapping, execute the function
combination_to_function[frozenset(current_keys)]()
def on_release(key):
# When a key is released, remove it from the set of keys we are keeping track of
current_keys.remove(key)
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
解决方案
推荐阅读
- javascript - 在javascript中按嵌套数组的索引过滤
- c++ - 如何检查函数是否没有做任何事情?
- python - Numpy sum 如何将二维数组的元素相加?
- node.js - 使用 JEST 测试 GET api (Express & Node.js, DM:sqlite)
- c++ - 为什么这个向量的实现不适用于字符串?
- python - 基于属性值在对象列表中获取对象引用的最佳方法
- deep-linking - Trust Wallet 中的 Deep Link 问题
- linux - Linux 上的蓝牙串行连接
- c# - 为什么我的对象在 ASP.NET Web 主机上托管的 ASP.NET 网站上的 SQL 数据库中插入 HTML 输入时为空
- c - 内存溢出?