PyAutoGui - Press key for X seconds

我怕爱的太早我们不能终老 提交于 2020-05-26 04:05:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!