如何在屏幕上注册键盘上按下的箭头?

How to register in the screen the arrows pressed on the keyboard?

我尝试在 python 中计算键盘上的箭头被按下的次数并在屏幕上显示给我,我不尝试做任何其他事情以免误解了,我想统计箭头被按下了多少次,因为我需要它来准确移动word中的一些元素。

我的来源:

from pynput import keyboard as kb

def pulsa(tecla):
    print('Se ha pulsado la tecla ' + str(tecla))

with kb.Listener(pulsa) as escuchador:
    escuchador.join()
from collections import defaultdict

count = defaultdict(int)

def pulsa(tecla):
    print('Se ha pulsado la tecla ' + str(tecla))
    count[tecla] += 1

(我假设 tecla 是可哈希的——如果不使用 count[str(tecla)] += 1。)

defaultdict 的作用是,我们第一次看到例如up_arrow, 它会假装已经有 0 up_arrow 的计数。 然后它只是从那里增加, 每次按向上箭头。


您可能会发现在击键处理程序中使用调试打印很方便:

from pprint import pp

def pulsa(tecla):
    count[tecla] += 1
    pp(count)