tags:

views:

2646

answers:

5

How to control mouse in Python, i.e. move it to certain position and click.

Thank you, Sasha

A: 

You'll really need to specify which GUI toolkit you're using in order to get a detailed answer. The specific answer depends on operating system, widget toolkit, and to some extent, which implementation of python you're using. In short, this is an unanswerable question.

Paul McMillan
I wotk in Windows and i don't use any toolkit. I am really new to Python and I never worked with any GUI before. Where I start from?
Sasha
Learn python first. Then worry about moving the mouse. GUI and UI in general should come AFTER you've got a firm grasp of your set of tools.
Paul McMillan
A: 

This has nothing to do with Python directly. You have to access the toolkits provided by the system. Have a look at the Windows API.

Georg
+3  A: 

Dont know python but perhaps a google would help

"Python controlling mouse movement" revealed this

http://danielbaggio.blogspot.com/2009/03/python-mouse-move-in-5-lines-of-code.html

from Xlib import X, display
d = display.Display()
s = d.screen()
root = s.root
root.warp_pointer(300,300)
d.sync()
Simon
This works in X. The OP works in windows.
Paul McMillan
+10  A: 

Tested on WinXP, Python 2.6 after installing pywin32 (pywin32-214.win32-py2.6.exe in my case):

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)
Jeffrey Kemp
`click(240, 240) # Bam, you're upvoted.`
eksortso
Thank you very much, It helps a lot!!!!
Sasha
Works perfectly. Nice.
Andrew Szeto
+7  A: 

You can use win32api or ctypes to call win32 api call, to control mouse or any gui.

A fun sample here to control mouse ;) using win32api

import win32api
import time
import math

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

a click using 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(3, 0, 0, 0,0) # left up
Anurag Uniyal
your ctypes code worked for me without any additional libraries! (python 2.6 on windows 7)
intrepion