本文介绍了PyAutoGui-按下键X秒钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个脚本,该脚本可以按 w,a,s,d 键以在任何游戏中移动角色。
为此,我需要在特定时间内按下 w 键。我如何实现呢?

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?

我想到了类似的东西:

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.keyDown()中的文档字符串所述:

As said in the doc-string from pyautogui.keyDown():

注意:出于某种原因,导致键重复,就像如果在文本字段上按住键盘键时
一样。

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.






您需要使用其他方法-您可以使用

或者,如果您希望使用 pyautogui ,您可以尝试执行以下操作:

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')

这篇关于PyAutoGui-按下键X秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 05:57