开发者

In python, how do you get it to input a keyboard press?

开发者 https://www.devze.com 2023-02-27 23:25 出处:网络
When I push the print screen button on my keyboard, I would like to trigger开发者_运维问答 an event, like this:

When I push the print screen button on my keyboard, I would like to trigger开发者_运维问答 an event, like this:

if keyboard-print screen:
    print "5"


Note that the tkinter solution does not work on Mac (at least it does not work on my Mac). I tested it with Python 3.2.2 and Python 2.7.2. If the window is withdrawn, it will not get the focus and therefore it will not sense any of the key events.


Tkinter has built-in keypress events.

import Tkinter as tk

def keypress(event):
if event.keysym == 'Escape':
root.destroy()
x = event.char
if x == "w":
print "blaw blaw blaw"
elif x == "a":
print "blaha blaha blaha"
elif x == "s":
print "blash blash blash"
elif x == "d":
print "blad blad blad"
else:
print x


root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', keypress)
# don't show the tk window
root.withdraw()
root.mainloop()


In windows you could use the msvcrt module:

This is a standard Windows-specific extension module. It defines a function kbhit() which checks whether a keyboard hit is present, and getch() which gets one character without echoing it.

I'm not sure however if it can work with these two combined keypresses


Tkinter is probably best, but if you're doing something terminal-based ncurses is also an option. And if you're using graphics or a GUI, the library you're using (PyGame, GTK, Wx, Qt, Pyglet etc.) will have its own way of dealing with keyboard events.

0

精彩评论

暂无评论...
验证码 换一张
取 消