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
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
#Infinite loops are dangerous.
while True: #Don't rely on this line of code too much and make sure to adapt this to your project.
if current_window == desired_window_name:
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
Python有一个keyboard模块,具有许多特性。安装它,可能需要使用以下命令:
然后在代码中使用它,如:
对于那些在windows上努力寻找工作答案的人,这里是我的:pynput
上述功能将打印您正在按下的任何键,并在释放“esc”键时启动操作。键盘文档是here,以便更灵活地使用
Markus von Broady突出显示了一个潜在的问题,即:此答案不要求您处于当前窗口中才能激活此脚本,windows的解决方案是:
使用
keyboard
模块可以做更多的事情。 您可以使用pip install keyboard
安装此模块 以下是一些方法:Method#1:
使用函数^{} :
这将在按下键p时中断循环
Method#2:
使用函数^{} :
它将等待您按p,然后继续按代码
Method#3:
使用函数^{} :
它需要一个回调函数。我使用了
_
,因为键盘函数将键盘事件返回给该函数一旦执行,它将在按键时运行该功能。通过运行以下命令行,可以停止所有挂钩:
Method#4:
这个方法已经被用户8167727回答过了,但我不同意他们编写的代码。它将使用函数^{} ,但以另一种方式:
当按下p时,它将中断循环
Method#5:
您也可以使用^{} 。它记录所有按下和释放的键,直到您按下} 元素列表
escape
键或在until
arg中定义的键,并返回^{注意事项:
keyboard
将从整个操作系统读取按键李>keyboard
在linux上需要root用户相关问题 更多 >
编程相关推荐