2

I need an event listener that starts and quits my script whenever I press a key. So this is a script that lets me know if a key has been pressed:

import Tkinter as tk

def onKeyPress(event):
    text.insert('end', 'You pressed %s\n' % (event.char, ))

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()

That works great but the problem is that I don't need a GUI. I should be able to press a key wherever I want. How would that be possible?

Reza Saadati
  • 5,018
  • 4
  • 27
  • 64
  • https://stackoverflow.com/questions/35223896/listen-to-keypress-with-asyncio#35514777 – erp Jul 06 '17 at 17:27
  • 2
    There are libraries that can do this, for example [keyboard](https://pypi.python.org/pypi/keyboard/). – Aran-Fey Jul 06 '17 at 17:34

1 Answers1

2

Like Rawing said, you can use the keyboard library, for example:

import keyboard
keyboard.add_hotkey('a', lambda: print "a was pressed")

Note that for this to work, the keyboard library must be installed, you can do this with $ sudo pip install keyboard
Edit: You might have to use $ sudo python -m pip install keyboard

Edit: Or you might have to use $ sudo py -m pip install keyboard

Edit: Or even $ sudo -H pip install keyboard

Also, note that I'm assuming you're using python 2.7.
Edit: if you wonder why I assumed you were using python 2.7 it was because you used from Tkinter import * in your GUI example, and in python 2.7, the tkinter module is called "Tkinter", whilst in python 3.6, tkinter is called "tkinter" so in python 3 you should use from tkinter import * (Note the lowercase "t" versus the capital "T" in tkinter/Tkinter)

Also, note that the keyboard module doesn't work on Mac (at least their pip page only says they support Windows and Linux, but it might work if you have luck)

Lastly, note that I haven't tried this myself since I currently do not have access to a computer with python installed. If it doesn't work, comment me and I'll try to find another solution :)
Edit: @RezaSaadati approved that it worked.

Joel Niemelä
  • 168
  • 1
  • 3
  • 13
  • Thank you very much for your answer. Unfortunately this doesn't work for me, since I get the error `AttributeError: module 'keyboard' has no attribute 'add_hotkey'`. I am using Python 3.6.1, maybe that's why?! Any chance I can get it worked on the current version? – Reza Saadati Jul 06 '17 at 20:53
  • 1
    The problem was I installed keyboard using git but now I used `py -m pip install keyboard` and it works perfectly well. Thank you very much for your great solution! – Reza Saadati Jul 06 '17 at 21:20
  • @RezaSaadati I'm happy it worked! Sorry for the late Reply, as you might have noticed, I added some extra edits to the answer, I would recommend you reading them :) – Joel Niemelä Jul 09 '17 at 13:05