问题
I'm currently working on a script that presses the 'w,a,s,d' keys in order to move a character in any game. For this to work, i need to have the 'w' key pressed for a specific amount of time. How can I achieve this?
I thought of something like:
pyautogui.keyDown('w')
time.sleep(2)
pyautogui.keyUp('w')
But this just pauses the whole program and no key is being pressed so this has no use to me.
回答1:
As said in the doc-string from 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.
You need a different approach - you can may use pygame - with this
Or, if you want to stay with pyautogui
you can try something like this:
def hold_W (hold_time):
import time, pyautogui
start = time.time()
while time.time() - start < hold_time:
pyautogui.press('w')
来源:https://stackoverflow.com/questions/48682388/pyautogui-press-key-for-x-seconds