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.
>>> pyautogui. press ('enter') # press the Enter key >>> pyautogui. press ('f1') # press the F1 key >>> pyautogui. press ('left') # press the left arrow key The press() function is really just a wrapper for the keyDown() and keyUp() functions, which simulate pressing a key down and then releasing it up.
These functions can be called by themselves. For example, to press the left arrow key three times while holding down the Shift key, call the following: >>> pyautogui.keyDown('shift') # hold down the shift key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') ...
>>> pyautogui.write('Hello world!') # prints out "Hello world!" instantly >>> pyautogui.write('Hello world!', interval=0.25) # prints out "Hello world!" with a quarter second delay after each character You can only press single-character keys with write (), so you can’t press the Shift or F1 keys, for example.
You may also want to check out all available functions/classes of the module pyautogui , or try the search function . def type(self, *keys_or_text): '''Type text and keyboard keys. See valid keyboard keys in `Press Combination`.
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')
with pyautogui.hold(key):
pyautogui.sleep(hold)
This will do the trick without making your own function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With