4

I'd like to know the simplest way to bind keys in python

for example, the default python console window apears and waits, then in psuedo ->

if key "Y" is pressed:
   print ("Yes")
if key "N" is pressed:
   print ("No")

I would like to achieve this without the use of any modules not included by python. just pure python

Any and all help is greatly appreciated

python 2.7 or 3.x Windows 7

Note: raw_input() requires the user to hit enter and is therefore not keybinding

DCA-
  • 1,262
  • 2
  • 18
  • 33

3 Answers3

6

From http://code.activestate.com/recipes/134892/ (although a bit simplified):

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        self.impl = _GetchUnix()
    def __call__(self): 
        return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys
    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

getch = _Getch()

Then you can do:

>>> getch()
'Y' # Here I typed Y

This is great as it doesn't need any 3rd party modules.

TerryA
  • 58,805
  • 11
  • 114
  • 143
  • which version of python is this intended for? – DCA- Jul 23 '13 at 10:51
  • Thanks! this will help alot :D – DCA- Jul 23 '13 at 10:57
  • The link(`code.activestate`) seems dead says bad request. Also should I do: `print(getch.__call__()) `@TerryA – alper Jun 16 '20 at 14:21
  • 1
    @alper Link still seems to work for me,and no you justneed to do `getch()` – TerryA Jun 18 '20 at 03:33
  • Thanks, link seems working but when I tried few more times I keep getting: `Bad Request Your browser sent a request that this server could not understand. Apache Server at aardvark.activestate.com Port 80` error. – alper Jun 18 '20 at 08:33
3

Well, the way to do it with Tkinter which is a module included in the python install is here:

from tkinter import *

window = Tk()
window.geometry("600x400")
window.title("Test")

def test(event):
    print("Hi")

window.bind("a", test)

window.mainloop()
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
0

If you have a screen, you might like this:

screen = turtle.Screen()
def blabla:
    # your code here
screen.listen()
screen.onkey(blabla, "(any key here)")
divibisan
  • 11,659
  • 11
  • 40
  • 58
Max
  • 1
  • Thanks for your post. Since this is an old question, it would help if you explained why someone might prefer your answer to one of the other existing answers. – divibisan May 30 '18 at 18:31
  • @divibisan, I don't know of a requirement that a question be new to add an answer to it, or that it has to be "better" than an existing answer for some reason. I appreciate alternate approaches in SO. However, I wish this answer worked out of the box. I've never seen turtle before and it'd be cool if the code above was an MWE. – user1717828 Nov 20 '20 at 11:59