基于Python繪制鍵盤按鍵使用次數(shù)的熱力圖
前言
刷掘金時(shí)候偶然看到了記錄下今天敲了多少下鍵盤,但是博主只是展示了統(tǒng)計(jì)出的鍵盤使用次數(shù),因此想到在這個(gè)idea上小改一下,實(shí)現(xiàn)鍵盤按鍵的熱力圖展示。
思路分析
- 按鍵記錄 這里可以使用 pynput 來偵聽鍵盤事件并記錄每次按鍵的計(jì)數(shù)。
- 數(shù)據(jù)存儲 使用一個(gè)字典來存儲按鍵次數(shù),其中鍵代表鍵盤鍵,值代表按下的次數(shù)。
- 可視化 使用 matplotlib 和 seaborn 庫可視化熱力圖。 您將把字典中的計(jì)數(shù)映射到色標(biāo),該色標(biāo)將顯示在代表 108 鍵鍵盤的布局上。
- 實(shí)時(shí)顯示 使用 tkinter 庫實(shí)時(shí)更新熱圖
具體實(shí)現(xiàn)
設(shè)置環(huán)境
首先安裝一些Python庫。pynput
庫將允許我們捕獲鍵盤事件,matplotlib
將使我們能夠創(chuàng)建熱圖可視化,tkinter
將用于構(gòu)建GUI。:
pip install pynput matplotlib tk
定義按鍵字典
這里我們需要預(yù)先使用字典存儲鍵盤中的全部按鍵的名字。
key_layout = [ ['Esc', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'PrtSc', 'Scroll', 'Pause'], ['`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 'Backsp', '', ''], ['Tab', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', '\', '', ''], ['Caps', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', "'", 'Enter', '', '', ''], ['Shift', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'Shift', '', '', '', ''], ['Ctrl', 'Win', 'Alt', 'Space', 'Alt', 'Fn', 'Menu', 'Ctrl', '', '', '', '', '', '', '', ''] ]
捕獲鍵盤輸入
pynput
可以以非阻塞方式監(jiān)聽鍵盤事件。保證程序可以在監(jiān)聽按鍵時(shí)繼續(xù)進(jìn)行其他任務(wù)(如更新GUI)。以下是如何為鍵盤事件設(shè)置監(jiān)聽器:
from pynput.keyboard import Listener def on_press(key): try: key_name = key.char.lower() if hasattr(key, 'char') and key.char is not None else key.name.lower() if key_name in key_counts: key_counts[key_name] += 1 update_heatmap() except AttributeError: pass listener = Listener(on_press=on_press) listener.start()
存儲和加載數(shù)據(jù)
這里我增加了個(gè)數(shù)據(jù)存儲功能,在每次關(guān)閉的時(shí)候?qū)?shù)據(jù)存儲到本地json文件中。load_data()
和save_data()
函數(shù)處理從文件中讀取和寫入數(shù)據(jù):
import json import os def load_data(): if os.path.exists('keyboard_data.json'): with open('keyboard_data.json', 'r') as file: return json.load(file) else: return {} def save_data(data): with open('keyboard_data.json', 'w') as file: json.dump(data, file, indent=4)
使用Matplotlib創(chuàng)建熱圖
使用matplotlib
來生成我們的熱圖:
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() heatmap = ax.imshow(np.zeros((6, 16)), cmap='hot', interpolation='nearest') for y, row in enumerate(key_layout): for x, key in enumerate(row): ax.text(x, y, key, ha='center', va='center', color='white')
使用Tkinter構(gòu)建GUI
這里使用了tkinter
來構(gòu)建一個(gè)簡單的UI界面。
import tkinter as tk from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg root = tk.Tk() root.title("Keyboard Heatmap") canvas = FigureCanvasTkAgg(fig, master=root) canvas_widget = canvas.get_tk_widget() canvas_widget.pack() root.mainloop()
界面效果如下:
處理程序關(guān)閉
為了確保在應(yīng)用程序關(guān)閉時(shí)保存數(shù)據(jù),我們連接到窗口的關(guān)閉事件:
def on_close(): save_data(data) root.destroy() root.protocol("WM_DELETE_WINDOW", on_close )
最終效果
最終代碼匯總
import tkinter as tk from pynput.keyboard import Listener import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import numpy as np import json from datetime import datetime import os key_layout = [ ['Esc', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'PrtSc', 'Scroll', 'Pause'], ['`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 'Backsp', '', ''], ['Tab', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', '\', '', ''], ['Caps', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', "'", 'Enter', '', '', ''], ['Shift', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'Shift', '', '', '', ''], ['Ctrl', 'Win', 'Alt', 'Space', 'Alt', 'Fn', 'Menu', 'Ctrl', '', '', '', '', '', '', '', ''] ] # Initialize key counts, ignoring empty strings key_counts = {key.lower(): 0 for row in key_layout for key in row if key} # File for storing the data data_file = 'keyboard_data.json' # Load historical data def load_data(): if os.path.exists(data_file): with open(data_file, 'r') as f: return json.load(f) else: return {} # Save data def save_data(data): with open(data_file, 'w') as f: json.dump(data, f, indent=4) # Current date current_date = datetime.now().strftime("%Y-%m-%d") data = load_data() if current_date not in data: data[current_date] = {key.lower(): 0 for row in key_layout for key in row if key} # Setup the matplotlib figure and axis fig, ax = plt.subplots(figsize=(12, 3)) heatmap = ax.imshow(np.zeros((6, 16)), cmap='hot', interpolation='nearest', vmin=0, vmax=10) ax.set_xticks([]) ax.set_yticks([]) # Adding key labels to the heatmap for y, row in enumerate(key_layout): for x, key in enumerate(row): if key: ax.text(x, y, key, ha='center', va='center', color='white', fontsize=8) # Function to update the heatmap def update_heatmap(): data_array = np.array([[data[current_date].get(key.lower(), 0) for key in row] for row in key_layout]) heatmap.set_data(data_array) canvas.draw_idle() # Key press callback def on_press(key): try: key_name = key.char.lower() if hasattr(key, 'char') and key.char is not None else key.name.lower() if key_name in data[current_date]: data[current_date][key_name] += 1 root.after(1, update_heatmap) except AttributeError: pass # Setup the tkinter window root = tk.Tk() root.title("Keyboard Heatmap") # Embed the matplotlib figure in the tkinter window canvas = FigureCanvasTkAgg(fig, master=root) canvas_widget = canvas.get_tk_widget() canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=True) # Start listening to the keyboard in the background listener = Listener(on_press=on_press) listener.start() # Shutdown hook to save data when the program is closed def on_close(): save_data(data) root.destroy() root.protocol("WM_DELETE_WINDOW", on_close) # Start the tkinter main loop root.mainloop()
到此這篇關(guān)于基于Python繪制鍵盤按鍵使用次數(shù)的熱力圖的文章就介紹到這了,更多相關(guān)Python鍵盤使用次數(shù)熱力圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深度學(xué)習(xí)環(huán)境配置之Anaconda安裝和pip源方式
這篇文章主要介紹了深度學(xué)習(xí)環(huán)境配置之Anaconda安裝和pip源方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02使用Python FastAPI構(gòu)建Web服務(wù)的實(shí)現(xiàn)
這篇文章主要介紹了使用Python FastAPI構(gòu)建Web服務(wù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06python中字符串String及其常見操作指南(方法、函數(shù))
String方法是用來處理代碼中的字符串的,它幾乎能搞定你所遇到的所有字符串格式,下面這篇文章主要給大家介紹了關(guān)于python中字符串String及其常見操作(方法、函數(shù))的相關(guān)資料,需要的朋友可以參考下2022-04-04python 定時(shí)器,實(shí)現(xiàn)每天凌晨3點(diǎn)執(zhí)行的方法
今天小編就為大家分享一篇python 定時(shí)器,實(shí)現(xiàn)每天凌晨3點(diǎn)執(zhí)行的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02