如何使用Python制作键盘热图?

问题描述 投票:0回答:1

基本上,我正在尝试制作一个键盘热图,它显示按键频率的各种颜色,现在在探索像 matplotlib 和 seaborn 这样的库之后,我不知道如何在 104 键布局的 .Png 图像上制作热图。 我已经创建了一个键盘记录器,并且能够将所有键记录在 .txt 文件中,其中普通键以 char 形式存储,但特殊键以 Keys.Space、Keys.LCtrl 等形式存储,现在我想在键盘热图上绘制按键的频率。 我不想使用像 tapmap 和 kbhmap 这样的库,因为它们只是将 .txt 文件作为输入并返回键盘热图的 png,但这样我将无法显示 ctrl、shift 和 backspace 的使用。 我该怎么办?

这是我的键盘记录器代码。

from pynput.keyboard import Key
from pynput.keyboard import Listener
the_keys = [] 
def functionPerKey(key):  
    the_keys.append(key)  
    storeKeysToFile(the_keys)

def storeKeysToFile(keys):
    with open('keylog.txt', 'w') as log:
        for the_key in keys:
            the_key = str(the_key).replace("'", "")
            log.write(the_key+'\n')
def onEachKeyRelease(the_key):
    if the_key == Key.esc:
        return False
with Listener(
    on_press = functionPerKey,
    on_release = onEachKeyRelease
) as the_listener:
    the_listener.join()```
python matplotlib keyboard heatmap pynput
1个回答
0
投票

您可以使用 keyboardlayout 显示键盘,并使用 matplotlib.cm.ScalarMappable 将颜色映射到击键计数(假设您已经有击键计数器):

import tkinter as tk
import tkinter.font as tkf

import keyboardlayout as kl
import keyboardlayout.tkinter as klt

import matplotlib
from matplotlib import cm

from random import randrange

# generating key Counter
counter = {k.name: randrange(20, 120000) for k in kl.Key if not k.name.endswith('_UPPER')}
# mapping colors:
norm = matplotlib.colors.Normalize(vmin=min(counter.values()), vmax=max(counter.values()))
mapper = cm.ScalarMappable(norm=norm, cmap=cm.YlGnBu)

key_size = 60

window = tk.Tk()
window.resizable(False, False)

# common options for keys
key_info_dict = {
    "margin": 5,
    #"color": "grey", letting color out so that it can be specified for each new key info profile
    "txt_color": "black",
    "txt_font": tkf.Font(family='Arial', size=key_size//4),
    "txt_padding": (key_size//6, key_size//10)
}
key_info = kl.KeyInfo(**key_info_dict, color="grey")

keyboard_layout = klt.KeyboardLayout(
    kl.LayoutName.QWERTY,
    kl.KeyboardInfo(position=(0,0), padding=2),
    (key_size, key_size),  # width, height,
    key_info,
    master=window
)

# converting rgba to hex string, e.g.: (0, 0, 255, 1) to #0000FF
def rgba_int_to_hex(rgba):
    hex_vals = list(map(lambda x: hex(int(255*x)), rgba))
    return f"#{hex_vals[0][2:]:0>2}{hex_vals[1][2:]:0>2}{hex_vals[2][2:]:0>2}"

# coloring each key individually
for k, v in counter.items():
    keyboard_layout.update_key(key=getattr(kl.Key, k), 
                            key_info=kl.KeyInfo(**key_info_dict, color=rgba_int_to_hex(mapper.to_rgba(v))))

window.mainloop()

输出(在我的例子中击键是完全随机的,所以这张地图根本不现实):

© www.soinside.com 2019 - 2024. All rights reserved.