3

"You've pressed the Enter Key!"

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

#Pseudocode:
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.

kilian579
  • 68
  • 2
  • 11
  • 2
    The mainloop is what makes it *possible* for Tkinter to respond to keyboard events at arbitrary times. Try `pynput`, it has the ability to install a keyboard listener (which is basically an event loop running in another thread), but note that callbacks from the listener will necessarily be running in that thread, NOT your main thread. – jasonharper Feb 27 '19 at 14:31

2 Answers2

5

Several Modules solve this Problem

Pynput (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
    pass

def on_release(key):
    #handle released keys
    if(key==Key.enter):
        function_x()

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

(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)


Tkinter

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)
root.mainloop()

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

kilian579
  • 68
  • 2
  • 11
0

No beans with module keyboard.

Simply way to clear screen:

print('\033[2J') # clear screen, but stay current cursor line
print('\033[H') # move cursor 1,1 home position

or

print('\033[H\033[2J') # one step to clear screen and move at home position

You may define function like:

def cls():
    print('\033[H\033[2J')

It works with tedious call braces.

I like to bind previous functionality to keyboard 'scroll lock' key, but how?

lemon
  • 14,875
  • 6
  • 18
  • 38