-1

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
Matiiss
  • 5,970
  • 2
  • 12
  • 29

2 Answers2

2

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
The Thonnu
  • 3,578
  • 2
  • 8
  • 30
0

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)
  • I think you need `global start` underneath `def pressed(key):` – The Thonnu Jul 23 '22 at 20:16
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 24 '22 at 19:54