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


当前回答

非常容易 1-安装包:

pip install mouse

2-添加库到项目:

import mouse

3-举个例子:

mouse.right_click()

在这个url中描述所有你可以使用它的函数:

https://github.com/boppreh/mouse

其他回答

尝试使用PyAutoGUI模块。多平台。

pip install pyautogui

所以:

import pyautogui
pyautogui.click(100, 100)

它还有其他特点:

import pyautogui
pyautogui.moveTo(100, 150)
pyautogui.moveRel(0, 10)  # move mouse 10 pixels down
pyautogui.dragTo(100, 150)
pyautogui.dragRel(0, 10)  # drag mouse 10 pixels down

这比浏览win32con的所有东西要容易得多。

尝试使用pyautogui,简单,也可以模拟键盘上的按键

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)

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

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

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

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

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

如果你需要玩游戏的话。正如本文https://www.learncodebygaming.com/blog/pyautogui-not-working-use-directinput中所解释的,像《我的世界》或《堡垒之夜》等游戏都有自己的鼠标/键盘事件注册方式。控制鼠标和键盘事件的方法是使用全新的PyDirectInput库。他们的github知识库是https://github.com/learncodebygaming/pydirectinput,有很多很棒的信息。 下面是一个快速的代码,执行鼠标循环,点击:

import pydirectinput  # pip install pydirectinput


pydirectinput.moveTo(0, 500)
pydirectinput.click()