2

I'm trying to create a piano keyboard in Python using Jazz-Plugin for sending the MIDI messages and Pynput listener to register the keystrokes.

My problem is that I want the lowest note to be on the Z key. I can't seem to find a way to get my if statement to recognise z, or any other alphanumeric keys when pressed. It DOES work with special keys, such as LCtrl.

I tried to find what data type key was. When key is a special character, the type is <enum 'Key'> but when it's an alphanumeric character it is <class 'pynput.keyboard._win32.KeyCode'>

This didn't work:

if key == pynput.keyboard._win32.KeyCode.z:

Replacing it with either 'z' or "'z'" or just z also doesn't work.

Here is the code:

def on_press(key):
    print(key, "pressed")
    if key == Key.ctrl_l:
        jazz.MidiOut(0x90, 30, 127)
    if key == "'z'":
        jazz.MidiOut(0x90, 60, 127)

def on_release(key):
    print(key, "released")
    if key == Key.esc:
        return False

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

When LCtrl is pressed the note plays as expected, and it prints Key.ctrl_l pressed. When z is pressed, it prints 'z' pressed but the note doesn't play. To me it doesn't make sense why it wouldn't recognise the keystroke.

Any help would be appreciated :)

N. Hooley
  • 41
  • 4

3 Answers3

2
if str(key) == "'z'":

it was this simple

N. Hooley
  • 41
  • 4
0

You can wrap a character around a KeyCode

>>> type(keyboard._win32.KeyCode.from_char('z'))
<class 'pynput.keyboard._win32.KeyCode'>
cmaureir
  • 285
  • 2
  • 8
0
from pynput.keyboard import KeyCode

if key == KeyCode.from_char('A'):
    print('A')
Miladiouss
  • 4,270
  • 1
  • 27
  • 34
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) will help people understand the reasons for your code suggestion. – Gerhard Nov 24 '21 at 07:27