はじめに
tkinterでbind関数を使用してキーバインドを行う際に、「押したキーがどのような値としてプログラム上で認識されているか」を確認する必要があり、押したキーを判定するスクリプトを作成し便利でしたので投稿します。
開発環境
・WSL2/Ubuntu環境
・Python: 3.10.12
押したキーを判定するスクリプト
PressKey_sample.py
import tkinter as tk
from tkinter import Text
# Determine pressed key
def Sample_PressKey(event):
print(f"Key: {event.keysym}")
# configure root
root = tk.Tk()
root.title("PressKey_sample")
root.geometry("800x600")
# make text
text = Text(root, wrap="word", undo=True)
text.pack(fill="both", expand=True)
# configure key-bind
root.bind("<Key>", Sample_PressKey)
root.mainloop()
プログラムの動作
キーを押すと、コンソール上に押したキーが値として出力されます。
Text領域も生成するようにしているので、テキストとしても入力した文字を確認できます。
参考文献
本記事は以下情報を参考にして執筆しました。