首页 > 解决方案 > 如何阻止在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()

标签: pythonpython-3.xinputpynput

解决方案


推荐阅读