PyAutoGui - 按键 X 秒
PyAutoGui - Press key for X seconds
我目前正在编写一个脚本,该脚本按下“w、a、s、d”键,以便在任何游戏中移动角色。
为此,我需要按下“w”键一段特定的时间。我怎样才能做到这一点?
我想到了类似的东西:
pyautogui.keyDown('w')
time.sleep(2)
pyautogui.keyUp('w')
但这只是暂停了整个程序,没有按键被按下,所以这对我没有用。
如 pyautogui.keyDown()
中的文档字符串所述:
Performs a keyboard key press without the release. This will put that
key in a held down state.
NOTE: For some reason, this does not seem to cause key repeats like would
happen if a keyboard key was held down on a text field.
您需要一种不同的方法 - 您可以使用 pygame - with this
或者,如果您想继续使用 pyautogui
,您可以尝试这样的操作:
def hold_W (hold_time):
import time, pyautogui
start = time.time()
while time.time() - start < hold_time:
pyautogui.press('w')
with pyautogui.hold(key):
pyautogui.sleep(hold)
这不需要创建您自己的函数就可以解决问题。
我目前正在编写一个脚本,该脚本按下“w、a、s、d”键,以便在任何游戏中移动角色。 为此,我需要按下“w”键一段特定的时间。我怎样才能做到这一点?
我想到了类似的东西:
pyautogui.keyDown('w')
time.sleep(2)
pyautogui.keyUp('w')
但这只是暂停了整个程序,没有按键被按下,所以这对我没有用。
如 pyautogui.keyDown()
中的文档字符串所述:
Performs a keyboard key press without the release. This will put that key in a held down state.
NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field.
您需要一种不同的方法 - 您可以使用 pygame - with this
或者,如果您想继续使用 pyautogui
,您可以尝试这样的操作:
def hold_W (hold_time):
import time, pyautogui
start = time.time()
while time.time() - start < hold_time:
pyautogui.press('w')
with pyautogui.hold(key):
pyautogui.sleep(hold)
这不需要创建您自己的函数就可以解决问题。