如何在Python中控制鼠标光标,即移动到特定位置并单击,在Windows下?
当前回答
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)
其他回答
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)
如果你想移动鼠标,使用这个:
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。
测试在WinXP, Python 2.6(3。在安装pywin32(在我的情况下是pywin32-214.win32-py2.6.exe)后:
import win32api, win32con
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)
快速和肮脏的函数,在Windows 7上使用ctypes库左键点击。无需下载。
import ctypes
SetCursorPos = ctypes.windll.user32.SetCursorPos
mouse_event = ctypes.windll.user32.mouse_event
def left_click(x, y, clicks=1):
SetCursorPos(x, y)
for i in xrange(clicks):
mouse_event(2, 0, 0, 0, 0)
mouse_event(4, 0, 0, 0, 0)
left_click(200, 200) #left clicks at 200, 200 on your screen. Was able to send 10k clicks instantly.
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)
推荐文章
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数
- 滚动或滑动窗口迭代器?
- python的方法找到最大值和它的索引在一个列表?
- 如何读取文件的前N行?
- 如何删除matplotlib中的顶部和右侧轴?