2

How can I detect key release with python 3 ?

Like if I pressed the key a for 1 second , when I remove my finger from the key ( releasing the key ) , It will print("Key 'a' pressed then released").

I trying to do it with module keyboard but I have no idea about how to use it for this. I used to detect keypress with it.
msvcrt module don't work for me but if msvcrt can do what I want , then you can answer me.

Note:

I Don't want to use Pygame or any other module which will show pop-ups

Community
  • 1
  • 1
Black Thunder
  • 5,331
  • 5
  • 22
  • 52
  • 1
    [this?](https://github.com/boppreh/keyboard#keyboard.on_release). You could follow a bit on the link you provided – Ma0 Aug 09 '17 at 08:05
  • 1
    Your module literally contains one example that does what you ask: https://github.com/boppreh/keyboard/blob/master/examples/pressed_keys.py – BoboDarph Aug 09 '17 at 08:15

3 Answers3

4

You can use the pynput module:

from pynput import keyboard

def on_key_release(key):
    print('Released Key %s' % key)

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

According to the documentation of pynput keyboard listener is a thread, which calls the function specified on on_release with the key argument. You can also specify a on_press function.

Edit:

As asked in discussions, you can stop the listener by returning false from the on_key_release function. Like that:

def on_key_release(key):
    print('Released Key %s' % key)
    return False
dpr
  • 8,675
  • 3
  • 32
  • 57
Franz Forstmayr
  • 900
  • 8
  • 27
3

You can use tkinter for it:

from tkinter import *
def keyup(e):
    print('up', e.char)
def keydown(e):
    print('down', e.char)

root = Tk()
frame = Frame(root, width=100, height=100)
frame.bind("<KeyPress>", keydown)
frame.bind("<KeyRelease>", keyup)
frame.pack()
frame.focus_set()
root.mainloop()
Black Thunder
  • 5,331
  • 5
  • 22
  • 52
Acafed
  • 31
  • 3
0

Similar to Acafed's answer, using tkinter and assuming you are using python3 you could easy do in this way:

from tkinter import Tk,Frame #importing only necessary stuff.

def keyrelease(e):
    print('The key was released: ', repr(e.char))

root = Tk()
f = Frame(root, width=100, height=100)
f.bind("<KeyRelease>", keyrelease)
f.pack()
root.mainloop()
decadenza
  • 1,612
  • 3
  • 13
  • 27