I am trying to create a start and stop button with a keyboard press

390 views Asked by At

I am using the keyboard library to create a button that starts and stops with the press of a button and I keep getting errors this is the code

while True:
    if keyboard.on_press('esc') == True:
        if start == 0:
            start = 1
        else:
            start = 0
    while start == 1:
        print('yes')
        sleep(1)

and this is the error im getting while pressing the 'p' key

yes
yes
Traceback (most recent call last):
  File "C:\Users\olawa\PycharmProjects\dj4e\venv\lib\site-packages\keyboard\_generic.py", line 22, in invoke_handlers
    if handler(event):
  File "C:\Users\olawa\PycharmProjects\dj4e\venv\lib\site-packages\keyboard\__init__.py", line 474, in <lambda>
    return hook(lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress)
TypeError: 'str' object is not callable
2

There are 2 answers

7
The Thonnu On

You need to pass a function to keyboard.on_press

Try:

def pressed(key):
    if key.name == 'esc':
        # Do something here

keyboard.on_press(pressed)

while True:
    # Do something else while you wait
2
Timmykiller5 On

it works now thanks

start = 1

def pressed(key):
    global start
    if key.name == 'esc':
        if start == 0 :
            start = 1
        elif start == 1:
            start = 0

keyboard.on_press(pressed)

while start == 1:
    print('yes')
    time.sleep(1)