2013-07-23 50 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()