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
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With