【问题标题】:Python key binding/capturePython键绑定/捕获
【发布时间】:2013-07-22 09:00:42
【问题描述】:

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

例如默认python控制台窗口出现并等待,然后在psuedo中->

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

我想使用任何不包含在python中的模块来实现这一点。纯python

非常感谢任何和所有帮助

python 2.7 或 3.x Windows 7

注意: raw_input() 需要用户按回车键,因此不是键绑定

【问题讨论】:

标签: python python-2.7 python-3.x keyboard


【解决方案1】:

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

那么你可以这样做:

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

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

【讨论】:

  • 这适用于哪个版本的python?
  • 谢谢!这将有很大帮助:D
  • 链接 (code.activestate) 似乎已死,表示请求不正确。我也应该这样做:print(getch.__call__()) @TerryA
  • @alper Link 似乎仍然对我有用,不,你只需要这样做getch()
  • 谢谢,链接似乎有效,但当我再试几次时,我不断收到:Bad Request Your browser sent a request that this server could not understand. Apache Server at aardvark.activestate.com Port 80 错误。
【解决方案2】:

好吧,使用 Tkinter(python 安装中包含的一个模块)的方法在这里:

from tkinter import *

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

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

window.bind("a", test)

window.mainloop()

【讨论】:

    【解决方案3】:

    如果你有屏幕,你可能会喜欢这样:

    screen = turtle.Screen()
    def blabla:
        # your code here
    screen.listen()
    screen.onkey(blabla, "(any key here)")
    

    【讨论】:

    • 感谢您的帖子。由于这是一个老问题,如果您解释为什么有人可能更喜欢您的答案而不是其他现有答案之一,这将有所帮助。
    • @divibisan,我不知道要求一个新问题才能为其添加答案,或者由于某种原因它必须比现有答案“更好”。我很欣赏 SO 中的替代方法。但是,我希望这个答案开箱即用。我以前从未见过海龟,如果上面的代码是 MWE,那就太酷了。
    猜你喜欢
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2015-06-01
    • 1970-01-01
    相关资源
    最近更新 更多