我正在使用pynput,我希望能够按住键,特别是wasd,但是当我尝试运行此代码时,它仅按下键并且不按住2秒钟。如果有人知道我在做什么错,请告诉我。谢谢
import time
keyboard = Controller()
time.sleep(2)
keyboard.press('w')
time.sleep(2)
keyboard.release('w')
答案 0 :(得分:1)
尝试使用“with”语句来保存您的密钥。 在我的示例中,它包含“alt”和制表符。
import time
from pynput.keyboard import Key, Controller
keyboard = Controller()
with keyboard.pressed(Key.alt):
keyboard.press(Key.tab)
time.sleep(1)
keyboard.press(Key.tab)
time.sleep(1)
keyboard.press(Key.tab)
time.sleep(1)
答案 1 :(得分:0)
也许尝试PyAutoGui。它更容易,并且可以在几行代码中使用。我从here
获得了代码>>> import pyautogui
>>> screenWidth, screenHeight = pyautogui.size()
>>> currentMouseX, currentMouseY = pyautogui.position()
>>> pyautogui.moveTo(100, 150)
>>> pyautogui.click()
>>> pyautogui.moveRel(None, 10) # move mouse 10 pixels down
>>> pyautogui.doubleClick()
>>> pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad) # use tweening/easing function to move mouse over 2 seconds.
>>> pyautogui.typewrite('Hello world!', interval=0.25) # type with quarter-second pause in between each key
>>> pyautogui.press('esc')
>>> pyautogui.keyDown('shift')
>>> pyautogui.press(['left', 'left', 'left', 'left', 'left', 'left'])
>>> pyautogui.keyUp('shift')
>>> pyautogui.hotkey('ctrl', 'c')
如果您只想按下一个键,那么请做
from pyautogui import*
from time import sleep
keyDown("a") #pressing down key 'a'
sleep() #how ever long you want
keyUp("a") #stop pressing key 'a' down
希望这会有所帮助。
答案 2 :(得分:0)
您可以进行两秒钟的循环。 (我没有足够的声誉来发表评论。)