2013-07-23 44 views
2

我想知道绑定在pythonPython的密钥绑定/捕获

例如按键最简单的方式,默认的Python控制台窗口apears和等待,然后在伪 - >

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

我想实现这个没有使用任何模块不包括在python中。只是纯粹的蟒蛇

任何及所有的帮助感激

蟒蛇2.7或3.x版的Windows 7

注:raw_input()要求用户按下回车键,因此没有键绑定

+0

这可能有助于http://stackoverflow.com/questions/510357/python-read-一个单一的字符从用户 –

回答

4

http://code.activestate.com/recipes/134892/(虽然有点简化):

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() 

然后y你可以这样做:

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

这很棒,因为它不需要任何第三方模块。

+0

哪个版本的python是用于此目的? –

+0

@ DCA-它适用于两个:)。 – TerryA

+0

谢谢!这将有助于:D –

1

那么,与Tkinter的做到这一点的方式是包含在Python安装模块是在这里:

from tkinter import * 

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

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

window.bind("a", test) 

window.mainloop()