对于那些在窗户上苦苦寻找有效答案的人,我的答案是:pynputfrom pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
上述功能将打印您按的任何键,并在您释放“esc”键时启动操作。键盘文档是here,用于更多变的用法。
Markus von Broady强调了一个潜在的问题,即:此答案不要求您处于激活此脚本的当前窗口中,windows的解决方案是:from win32gui import GetWindowText, GetForegroundWindow
current_window = (GetWindowText(GetForegroundWindow()))
desired_window_name = "Stopwatch" #Whatever the name of your window should be
if current_window == desired_window_name:
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()