user18055567
user18055567

Reputation:

pynput attribute error "key" object has no attribute "char"

I'm using this keyboard listener thread:

listener = keyboard.Listener(
  on_press=on_press,
  on_release=on_release)
listener.start()

Heres how my on_press() & on_release() functions:

def on_press(key):
  if key.char == (A1_bind):
    A1.config(bg=pad_active, fg=pad_active)
    banklights.itemconfig(bank_a_light, fill=banklight_active)
    print("Pad A1 Triggered")
def on_release(key):
  if key.char == (A1_bind):
    A1.config(bg=pad, fg=pad)
    banklights.itemconfig(bank_a_light, fill=banklight)

Heres my error message when I press keys like ctrl, alt, tab etc:

AttributeError: 'Key' object has no attribute 'char'

Please help me to fix this so when one of those keys listed above do not trigger this error.

Upvotes: 0

Views: 2061

Answers (1)

Etienne Chauveau
Etienne Chauveau

Reputation: 11

This happens because key is not the same object depending if the key pressed was a character or a special key (like ctrl or f11). If it was a apecial key, it would not have a char attribute. I don't know the details of this, maybe someone else can explain.

Putting your if statement in a try and except block should help, something like this :

def on_press(key):
    try:
        if key.char == (A1_bind):
            A1.config(bg=pad_active, fg=pad_active)
            banklights.itemconfig(bank_a_light, fill=banklight_active)
            print("Pad A1 Triggered")
    except:
        #do something else

Upvotes: 1

Related Questions