Detect key input in Python

前端 未结 4 1199
有刺的猬
有刺的猬 2020-12-08 06:10

(In 2013) I don\'t know why Python is that weird, you can\'t find this by searching in google very easily, but it\'s quite simple.

How can I detect \'SPACE\

相关标签:
4条回答
  • 2020-12-08 06:17

    You could make a little Tkinter app:

    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()
    
    0 讨论(0)
  • 2020-12-08 06:19

    use the builtin: (no need for tkinter)

    s = input('->>')
    print(s) # what you just typed); now use if's 
    
    0 讨论(0)
  • 2020-12-08 06:20

    Key input is a predefined event. You can catch events by attaching event_sequence(s) to event_handle(s) by using one or multiple of the existing binding methods(bind, bind_class, tag_bind, bind_all). In order to do that:

    1. define an event_handle method
    2. pick an event(event_sequence) that fits your case from an events list

    When an event happens, all of those binding methods implicitly calls the event_handle method while passing an Event object, which includes information about specifics of the event that happened, as the argument.

    In order to detect the key input, one could first catch all the '<KeyPress>' or '<KeyRelease>' events and then find out the particular key used by making use of event.keysym attribute.

    Below is an example using bind to catch both '<KeyPress>' and '<KeyRelease>' events on a particular widget(root):

    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()
    
    0 讨论(0)
  • 2020-12-08 06:32

    Use Tkinter there are a ton of tutorials online for this. basically, you can create events. Here is a link to a great site! This makes it easy to capture clicks. Also, if you are trying to make a game, Tkinter also has a GUI. Although, I wouldn't recommend Python for games at all, it could be a fun experiment. Good Luck!

    0 讨论(0)
提交回复
热议问题