Ali Mohammad
Ali Mohammad

Reputation: 41

how to keep printing a string when holding a certain key

import keyboard

while True:
    if keyboard.is_pressed('b'):
        print('a')
        break

This is my code it prints a when I press b. but I want it to keep printing a when I'm holding b how do I do this.

Upvotes: 3

Views: 156

Answers (2)

darren
darren

Reputation: 5734

I use this module pynput mostly for mouse events, but it handles keyboard events too.

Here is the link: https://pypi.org/project/pynput/

This library allows you to control and monitor input devices. Currently, mouse and keyboard input and monitoring are supported.

Instruction for keyboard midway down the page:

from pynput.keyboard import Key, Controller
keyboard = Controller()

or more appropriately use pynput.keyboard.Listener like this:

from pynput import keyboard

The code below detects multiple inputs. You would have to modify it for the a to b example given in the original question.

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()

Thank you.

Upvotes: 1

Shawn Ramirez
Shawn Ramirez

Reputation: 833

How about adding a small delay after the print function to allow the program to re-evaluate if the input is still being pressed?

import keyboard
import time

while True:
    if keyboard.is_pressed('b'):
        print('a')
        time.sleep(0.1)
    

Upvotes: 0

Related Questions