source

Python으로 마우스 제어

goodcode 2022. 9. 11. 17:15
반응형

Python으로 마우스 제어

Python에서 마우스 커서를 어떻게 제어합니까? 즉, Windows에서 마우스 커서를 특정 위치로 이동하고 클릭하는 것입니까?

pywin32(내 경우 pywin32-214.win32-py2.6.exe)를 설치한 후 WinXP에서 테스트된 Python 2.6(3.x도 테스트 완료):

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)

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 관련 작업보다 훨씬 쉽습니다.

사용할 수 있습니다.win32api또는ctypes마우스 또는 임의의 GUI를 제어하기 위해 win32 apis를 사용하는 모듈

다음은 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)

ctype을 사용한 클릭:

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

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 문서

특징들

  • 모든 마우스 디바이스의 글로벌이벤트 훅(포커스에 관계없이 이벤트를 캡처합니다).
  • 마우스 이벤트를 수신 및 전송합니다.
  • WindowsLinux에서 동작합니다(sudo 필요).
  • Pure Python, 컴파일할 C 모듈이 없습니다.
  • 의존 관계가 없습니다.인스톨과 도입은 간단하며, 파일을 카피하기만 하면 됩니다.
  • 파이썬 2 및 3
  • 높은 수준의 API(녹음 및 재생 등)를 포함합니다.
  • 별도의 스레드에서 자동으로 캡처되는 이벤트는 기본 프로그램을 차단하지 않습니다.
  • 테스트 및 문서화 완료.

인스톨

  • Windows:pip install mouse
  • Linux:sudo pip install mouse

또 다른 옵션은 크로스 플랫폼 AutoPy 패키지를 사용하는 것입니다.이 패키지에는 마우스를 이동하기 위한 두 가지 옵션이 있습니다.

이 코드 조각은 커서를 즉시 위치(200,200)로 이동합니다.

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

대신 커서가 화면에서 특정 위치로 가시적으로 이동하도록 하려면 smooth_move 명령을 사용할 수 있습니다.

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

리눅스

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/

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)

어디서나 좌클릭할 수 있는 빠르고 더러운 기능clicksWindows 7에서 라이브러리를 사용하여 시간을 설정합니다.다운로드가 필요 없습니다.

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.

받아들여진 답변은 나에게 효과가 있었지만, 그것은 불안정했다(클릭이 재지정되지 않을 때가 있다). 그래서 나는 MUSEEVENTF_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)

또 다른 대안으로는 마우스 라이브러리가 있는데, 비교적 단순하고 크로스 플랫폼이기 때문에 개인적으로 사용하고 있습니다.

사용 방법은 다음과 같습니다.

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에서 마우스를 제어하는 방법

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)

매우 간단한 1-설치 패키지:

pip install mouse

2- 프로젝트에 라이브러리 추가:

import mouse

3- 예를 들어 다음과 같이 사용합니다.

mouse.right_click()

다음 URL에서 사용할 수 있는 모든 기능을 설명합니다.

https://github.com/boppreh/mouse

마우스를 이동하려면 다음을 사용합니다.

import pyautogui
pyautogui.moveTo(x,y)

클릭하는 경우는, 다음을 사용합니다.

import pyautogui
pyautogui.click(x,y)

★★★가pyautogui과 같이 입력합니다.CMD는 CMD에 접속합니다.pip install pyautogui

★★★★★★★★★★★★가 인스톨 됩니다.pyautoguiPython 2.x の python python python python python python python.

3. Python 3.x를 .pip3 install pyautogui ★★★★★★★★★★★★★★★★★」python3 -m pip install pyautogui.

화면에서 마우스 랜덤 이동

화면 해상도에 따라 화면에서 마우스를 임의로 이동합니다.아래 코드를 확인합니다.

pip install pyautogui을 사용하다

import pyautogui
import time
import random as rnd

#calculate height and width of screen
w, h = list(pyautogui.size())[0], list(pyautogui.size())[1]

while True:
    time.sleep(1)
    #move mouse at random location in screen, change it to your preference
    pyautogui.moveTo(rnd.randrange(0, w), 
                     rnd.randrange(0, h))#, duration = 0.1)

게임으로 작업해야 할 경우.이 게시물 https://www.learncodebygaming.com/blog/pyautogui-not-working-use-directinput,에서 설명한 바와 같이 Minecraft나 Fortnite와 같은 일부 게임에는 마우스/키보드 이벤트를 등록하는 고유한 방법이 있습니다.마우스와 키보드의 이벤트를 제어하려면 최신 PyDirectInput 라이브러리를 사용합니다.그들의 github 저장소는 https://github.com/learncodebygaming/pydirectinput,이며 많은 훌륭한 정보를 가지고 있다.
여기 마우스 루프는 빠른 코드, 클릭: 있다.다음은 마우스를 루프하고 클릭하는 빠른 코드입니다.

import pydirectinput  # pip install pydirectinput


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

pyautogui를 사용해보세요, 쉽고, 키보드에서도 키를 누르는 시뮬레이션을 할 수 있습니다.

언급URL : https://stackoverflow.com/questions/1181464/controlling-mouse-with-python

반응형