-1

I am trying to use the enter key to show different text after pressing it

from pynput.keyboard import Key, Listener
k=0
def on_press(key):
   pass
def on_release(key):
   if key==Key.enter:
      k=k+1
with Listener(on_press=on_press, on_release=on_release) as listner :
  listner.join()

for i in range (10):
     print(k)

I dont know why it does not print anything. I'm expecting the following:

1
2
3
4
5
6
7
8
9
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
anas
  • 1
  • 1

2 Answers2

1

In Python is a concept named indentation. Other languages use for example { and }. If you want to read more on this topic, try this link. So your loop is not indented properly, what you can see in this error message:

  File "/projects/stackoverflow_70635220.py", line 11
    for i in range (10):
                        ^
IndentationError: unindent does not match any outer indentation level

Second, using listener.join() waits for the listener to terminate, what it doesn't and shouldn't do. So if you want to handle any key events, do that inside the listener functions on_press and on_release.

Furthermore, in your on_release-method, you are trying to increment the variable k. This is not possible due to the fact, that the variable is not writable in the scope of your function. If you want to learn more about scopes in python, look here.

You can fix the last issue by writing global k inside your on_release method.

A final code example could look something like this:

from pynput.keyboard import Key, Listener
   
k=0

def on_press(key):
    pass

def on_release(key):
    global k
    if key==Key.enter:
        k=k+1      
        print(k)
        

with Listener(on_press=on_press, on_release=on_release) as listener :
        listener.join()
Bloeckchen
  • 65
  • 6
0

You need to use the global modifier or else you will get a reference before assignment error. The reason for this is that within the local scope of your on_release() function, k=k+1 is interpreted as a reference to a local variable k, which doesn't exist. By using the global keyword you are telling python to use the k that exists outside of this scope.

The below code should work as you expected

from pynput.keyboard import Key, Listener

k = 0

def on_press(key):
    pass

def on_release(key):
    if key == Key.enter:
        global k
        k = k + 1

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

for i in range(10):
    print(k)
Ewan Brown
  • 640
  • 3
  • 12