PyAutoGUI Shift-Down 什么都不做

PyAutoGUI Shift-Down does Nothing

我有以下脚本,旨在每 5 秒截取一次视频截图,然后按右移键快进到下一个 5 秒间隔,重复。看起来 shiftdown 不起作用,因为每当我手动执行它时,它都会起作用,但每当我 运行 脚本时,右键都起作用但没有 shift。

time.sleep(2)

while t < 20:
    time.sleep(0.5)
    pyautogui.keyDown('shiftleft')
    time.sleep(0.5)
    pyautogui.press('right')
    pyautogui.keyUp('shiftleft')
    time.sleep(2)
    screenshot = pyautogui.screenshot()
    screenshot.save(loc + str(t) + '.png')
    t = t + 1

time.sleep(0.5)

我认为您应该改用 pyautogui.hotkey() 函数。

像这样:

import pyautogui as pe

pe.hotkey('shift', 'left)

它基本上做同样的事情,它按下 shift 键和左键并做这件事。

如果您正在使用 Windows 并且如果您愿意尝试不同的模块,pydirectinput seems to work better than pyautogui for <shift>+<arrow> key operations. I got the idea from

下面的示例使用记事本的打开副本。在记事本中, + 将 select 文本。要使此示例生效,您需要在文件中添加一些 space,并且光标必须位于至少一个 space.

的左侧
import pyautogui
import pydirectinput
import time

mywin = pyautogui.getWindowsWithTitle("Notepad")[0]

mywin.activate()
time.sleep(2)

pydirectinput.keyDown('shift')
pydirectinput.press('right')
pydirectinput.keyUp('shift')

这是另一个不需要安装 pydirectinput 的答案。此答案仅适用于 Windows。来自 this question, having numlock or caps lock activated will break <shift> + <arrow> in pyautogui. To get around this, you'll have to detect if either numlock or capslock is active. To do that, you'll have to do Windows API calls. You can do the calls with built-in ctypes or pywin32

中的评论

这里有一个 ctypes 的例子(ctypes 代码改编自 this answer):

import pyautogui
import time

mywin = pyautogui.getWindowsWithTitle("Notepad")[0]

mywin.activate()
time.sleep(2)

import ctypes
VK_CAPITAL = 0x14
VK_NUMLOCK = 0x90
user32 = ctypes.WinDLL('user32.dll')

if user32.GetKeyState(VK_CAPITAL):
    # numlock is active, need to deactivate it before using <shift>+<arrow>
    capslock = True
    pyautogui.press('capslock')
else:
    capslock = False

if user32.GetKeyState(VK_NUMLOCK):
    # capslock is active, need to deactivate it before using <shift>+<arrow>
    numlock = True
    pyautogui.press('numlock')
else:
    numlock = False

pyautogui.keyDown('shift')
pyautogui.press('right')
pyautogui.keyUp('shift')

if capslock:
    pyautogui.press('capslock')

if numlock:
    pyautogui.press('numlock')