Binding a Keyboard Key to a Function – Python KeyListener


“You’ve pressed the Enter Key!”

Whenever I press Key(z) the function should be executed:

bind(<Enter>, function_x)

I’m currently working on a python program, which will run in a constant loop. It runs only on the console (no GUI), but still I need to be able to interact with the program at any time without having the program asking for input.


Several Modules solve this Problem

(pip install pynput)

Simple module for handling and controlling general inputs

from pynput import keyboard
from pynput.keyboard import Key

def on_press(key):
    #handle pressed keys

def on_release(key):
    #handle released keys

with keyboard.Listener(on_press=on_press,on_release=on_release) as listener:

(See pynput docs)

Keyboard (pip install keyboard)

A simple module for simulating and handling keyboard input

keyboard.add_hotkey('enter', lambda: function_x())

(See Keyboard docs)


Integrated UI Module, can track inputs on focused thread

from tkinter import Tk
root = Tk() #also works on other TK widgets
root.bind("<Enter>", function_x)

Be aware: These solutions all use Threading in some way. You might not be able to execute other code after you’ve started listening for keys.

Helpful threads:
KeyListeners, Binding in Tkinter

feel free to add more solutions

Answered By – kilian579

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published