如何在Python中控制鼠标光标,即移动到特定位置并单击,在Windows下?


当前回答

另一种选择是使用跨平台AutoPy包。这个包有两个不同的选项来移动鼠标:

这段代码片段将立即将光标移动到(200,200)位置:

import autopy
autopy.mouse.move(200,200)

如果你想让光标在屏幕上移动到一个给定的位置,你可以使用smooth_move命令:

import autopy
autopy.mouse.smooth_move(200,200)

其他回答

Pynput是我发现的最好的解决方案,无论是Windows还是Mac。超级容易编程,工作得非常好。

例如,

from pynput.mouse import Button, Controller

mouse = Controller()

# Read pointer position
print('The current pointer position is {0}'.format(
    mouse.position))

# Set pointer position
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
    mouse.position))

# Move pointer relative to current position
mouse.move(5, -5)

# Press and release
mouse.press(Button.left)
mouse.release(Button.left)

# Double click; this is different from pressing and releasing
# twice on Mac OSX
mouse.click(Button.left, 2)

# Scroll two steps down
mouse.scroll(0, 2)

查看跨平台PyMouse: https://github.com/pepijndevos/PyMouse/

另一种选择是鼠标库,我个人使用它,因为它相对简单和跨平台。

下面是你如何使用它:

import mouse
# move 100 right and 100 down with a duration of 0.5 seconds
mouse.move(100, 100, absolute=False, duration=0.5)
# left click
mouse.click('left')
# right click
mouse.click('right')

这是来源:如何在Python中控制鼠标

你可以使用win32api或ctypes模块来使用win32api来控制鼠标或任何gui

下面是一个使用win32api控制鼠标的有趣例子:

import win32api
import time
import math

for i in range(500):
    x = int(500+math.sin(math.pi*i/100)*500)
    y = int(500+math.cos(i)*100)
    win32api.SetCursorPos((x,y))
    time.sleep(.01)

使用ctypes进行单击:

import ctypes

# see http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx for details
ctypes.windll.user32.SetCursorPos(100, 20)
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up
import ctypes
from time import sleep

SetCursorPos = ctypes.windll.user32.SetCursorPos
print("Woohoo!\nTake Rest!\nMouse pointer will keep moving!\n\nPress ctrl+c to stop...!")
while True:
    SetCursorPos(300, 300)
    sleep(2)
    SetCursorPos(500, 500)
    sleep(4)