检测pyautogui是否按下了键



如何检查python是否按下了键?键盘。Is_pressed不工作,可能是因为它不是从键盘上按下的。

import pyautogui
import keyboard
pyautogui.keyDown('shift')
if keyboard.is_pressed('shift') == True:
print('Shift is down')
else:
print('Shift is up')

pyautogui.keyUp('shift')

这是因为它只执行一次,这是当代码被执行。您可以使用while循环,它将在每一帧执行。但我建议创建一个"等到"函数,这意味着它将等待,直到条件为真。你可以做的例子:

import time

def wait_until(condition):
while not condition:
time.sleep(0.1)  # Adjust the delay as needed
# Condition is now true, continue with the rest of your code

# Example usage
x = 0
wait_until(lambda: x > 5)
print("x is now greater than 5")

所以,在你的情况下,我们不需要那个,但我已经告诉了这个,因为它非常重要!顺便说一下,代码应该是这样的:

import time
import pyautogui
import keyboard

while True:
if keyboard.is_pressed('shift') == True:
print('Shift is down')
else:
print('Shift is up')

如果它不工作,你可以评论这篇文章,我会回复你的更正!

最新更新