1

I'm writing a very simple piece of code.

  • I want to listen to the keyboard.
  • When I press F11, the message "Activated..." must be displayed, just once.
  • When I press F11 again, the message "Deactivated..." must be displayed, also just once.
  • And so on...
  • When I press F12, I want the listener to stop.

Here's my piece of code and I'm having troubles to find the right implementation to avoid the constant loop ("Activated... Deactivated... Activated... Deactivated...") when I press F11.

Also, any advice to have a better implementation, more state-of-the-art, more pythonic, is welcome!

# -*- coding: utf-8 -*-

from pynput import keyboard

is_active = False

def on_press(key):
    global is_active
    # Activate/Deactivate when pressing F11
    if key == keyboard.Key.f11:
        if is_active:
            is_active = False
            print("Deactivate...")
        else:
            is_active = True
            print("Activate...")
    # Stop "on_press" listener
    if key == keyboard.Key.f12:
        return False

with keyboard.Listener(on_press=on_press) as listener:
    listener.join()
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

You're going to want to use

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

When you hold down on a key you will get multiple events just like if you hold down the aaaaaaaaaaaaaaaaaaaaaaaaaaa key without letting up. You need to set up a locking mechanism where the first time it's pressed you don't let it happen again until you release the key.

Modified code:

# -*- coding: utf-8 -*-

from pynput import keyboard

is_active = False
is_f11_pressed = False

def on_press(key):
    global is_f11_pressed
    global is_active
    # Activate/Deactivate when pressing F11
    if key == keyboard.Key.f11 and not is_f11_pressed:
        is_f11_pressed = True
        if is_active:
            is_active = False
            print("Deactivate...")
        else:
            is_active = True
            print("Activate...")
    # Stop "on_press" listener
    if key == keyboard.Key.f12:
        return False

def on_release(key):
    global is_f11_pressed
    if key == keyboard.Key.f11:
        is_f11_pressed = False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
Will Bender
  • 155
  • 6