pyautogui-按键x秒

发布于 2025-01-23 17:35:15 字数 254 浏览 1 评论 0原文

我目前正在编写一个脚本,该脚本按“ w,a,s,d ”键,以便在任何游戏中移动角色。 为此,我需要将' w '键施加特定时间。我该如何实现?

我想到了类似的事情:

pyautogui.keyDown('w')
time.sleep(2)
pyautogui.keyUp('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?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情徒 2025-01-30 17:35:15

pyautogui.keydown()的文档弦乐中所述:

执行键盘键,而无需发布。这会把
钥匙处于截止状态。

注意:出于某种原因,这似乎不会引起关键重复
如果在文本字段上键入键盘键,就会发生。


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

或,如果您想留下pyautogui,则可以尝试这样的事情:

def hold_W (hold_time):
    import time, pyautogui
    start = time.time()
    while time.time() - start < hold_time:
        pyautogui.press('w')

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')
闻呓 2025-01-30 17:35:15
with pyautogui.hold(key):
    pyautogui.sleep(hold)

这将在不做自己的功能的情况下解决问题。

with pyautogui.hold(key):
    pyautogui.sleep(hold)

This will do the trick without making your own function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文