import keyboard # using module keyboard
while True: # making a loop
try: # used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except:
break # if user pressed a key other than the given key the loop will break
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()
Python有一个具有许多特性的keyboard模块。安装它,可能使用以下命令:
然后在代码中使用它,比如:
正如OP提到的raw_输入-这意味着他想要cli解决方案。 Linux:你想要的是curses(windows PDCurses)。Curses,是一个用于cli软件的图形API,您可以实现不仅仅是检测关键事件。
此代码将检测按键,直到按下新行。
对于那些在窗户上苦苦寻找有效答案的人,我的答案是:pynput
上述功能将打印您按的任何键,并在您释放“esc”键时启动操作。键盘文档是here,用于更多变的用法。
Markus von Broady强调了一个潜在的问题,即:此答案不要求您处于激活此脚本的当前窗口中,windows的解决方案是:
相关问题 更多 >
编程相关推荐