2013-07-23 2 views
2
내가 예를 들어

파이썬은 키 바인딩/캡처

파이썬에서 키를 결합하는 가장 간단한 방법을 알고 싶습니다

는 기본 파이썬 콘솔 창 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- a-single-character-from-the- –

답변

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

어떤 파이썬 버전이이 용도입니까? –

+0

@ DCA- 둘 다 작동합니다. :). – TerryA

+0

감사! 이것은 많이 도움이 될 것입니다 : D –

1

음, Tkinter를 함께 할 수있는 방법은 여기에 있습니다 :

from tkinter import * 

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

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

window.bind("a", test) 

window.mainloop()