Tkinter: how to use pynput keyboard listener together with tkinter GUI
In documentation you can see example for pynput Monitoring The keyboard
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
which blocks code but you can put code between lines
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
# ... your code ...
listener.join()
or you can run it as
listener = keyboard.Listener(on_press=on_press, on_release=on_release)
listener.start()
# ... your code ...
listener.stop()
With thinter it can be
import tkinter as tk
from pynput.keyboard import Listener, Key
# --- functions ---
def on_press(key): # `key` can be `Key` (which doesn't have `char`) or `KeyCode` (which have `char`)
global listen
#print(str(key) == "'1'", str(key))
#if key == Key.esc:
if str(key) == 'Key.esc':
listen = not listen
if listen:
#if hasattr(key, 'char') and key.char == '1': # there is no `Key.1` and `1`
if str(key) == "'1'": # it needs `' '` in string
label_var.set(label_var.get()+'1')
print('1!')
# --- main ---
listen = False
root = tk.Tk()
label_var = tk.StringVar()
label = tk.Label(root, textvariable=label_var, width=10)
label.pack()
listener = Listener(on_press=on_press)
print('start')
listener.start()
listener.wait()
print('mainloop')
root.mainloop()
print('stop')
listener.stop()
print('end')
# without `listener.join()` because it runs as `daemon`
If you like it
Buy a Coffee
