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


当前回答

如果你想移动鼠标,使用这个:

import pyautogui
pyautogui.moveTo(x,y)

如果你想点击,使用这个:

import pyautogui
pyautogui.click(x,y)

如果你没有安装pyautogui,你必须将python附加到CMD。进入CMD并输入:pip install pyautogui

这将为Python 2.x安装pyautogui。

对于Python 3。X,你可能不得不使用pip3 install pyautogui或python3 -m PIP install pyautogui。

其他回答

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)

接受的答案为我工作,但它是不稳定的(有时点击不会注册),所以我添加了一个额外的MOUSEEVENTF_LEFTUP。然后它就可靠地工作了

import win32api, win32con
def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0) 
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)

Linux

from Xlib import X, display
d = display.Display()
s = d.screen()
root = s.root
root.warp_pointer(300,300)
d.sync()

来源:Python鼠标移动5行代码(仅适用于Linux)。

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

从2022年开始,你可以使用鼠标:

import mouse
mouse.move("500", "500")
mouse.click() # default to left click
# mouse.right_click()
# mouse.double_click(button='left')
# mouse.double_click(button='right')
# mouse.press(button='left')
# mouse.release(button='left')

完整的Api文档

特性

所有鼠标设备上的全局事件钩子(捕获事件而不管 聚焦)。 监听并发送鼠标事件。 适用于Windows和Linux(需要sudo)。 纯Python,不需要编译C模块。 零依赖关系。简单的安装和部署,只需复制 文件。 Python 2 / 3 包括高级API(例如记录和播放)。 事件自动捕获在单独的线程,不阻塞主 程序。 测试并记录。


安装

Windows: pip安装鼠标 Linux: sudo pip install mouse