(2013年)我不知道为什么Python那么怪异,你很难在谷歌上找到这个,但它其实很简单。
如何检测“空格”或者其他按键呢? 我该如何做到这一点:
print('You pressed %s' % key)
这应该被包含在Python核心中,请不要链接与核心Python无关的模块。
您可以制作一个小的Tkinter应用程序:
import Tkinter as tk
def onKeyPress(event):
text.insert('end', 'You pressed %s\n' % (event.char, ))
root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()
使用Tkinter,网上有很多相关的教程。基本上,您可以创建事件。这是一个链接到link一个伟大的网站!这使得捕获点击很容易。此外,如果你想做一个游戏,Tkinter也有一个GUI。虽然我不建议Python用于游戏,但它可能是一个有趣的实验。祝你好运!
按键输入是一种预定义事件。您可以通过使用现有的绑定方法(bind
, bind_class
, tag_bind
, bind_all
)将event_sequence
(s)附加到event_handle
(s)上来捕获事件。为了做到这一点:
event_handle
方法event_sequence
)当事件发生时,所有这些绑定方法隐式调用event_handle
方法,同时将包含有关发生的事件的具体信息的Event
对象作为参数传递。
为了检测按键输入,可以首先捕获所有'<KeyPress>'
或'<KeyRelease>'
事件,然后利用event.keysym
属性找出所使用的特定按键。
下面是一个使用bind
在特定小部件(root
)上捕获'<KeyPress>'
和'<KeyRelease>'
事件的示例:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def event_handle(event):
# Replace the window's title with event.type: input key
root.title("{}: {}".format(str(event.type), event.keysym))
if __name__ == '__main__':
root = tk.Tk()
event_sequence = '<KeyPress>'
root.bind(event_sequence, event_handle)
root.bind('<KeyRelease>', event_handle)
root.mainloop()
s = input('->>')
print(s) # what you just typed); now use if's
if s == ' ':
...
getch
方法可能更好。 - unutbu