Python键绑定/捕获 [英] Python key binding/capture

查看:73
本文介绍了Python键绑定/捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在python中绑定键的最简单方法

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

例如,默认的python控制台窗口会先提示并等待,然后在psuedo->

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

我想在不使用python未包含的任何模块的情况下实现 的这种实现.只是纯python

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或3.x Windows 7

python 2.7 or 3.x Windows 7

注意: raw_input()要求用户按Enter键,因此不能进行键盘绑定

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

推荐答案

来自 http://code. activestate.com/recipes/134892/(尽管有些简化):

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.

这篇关于Python键绑定/捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆