Intercepting Mouse Movements
You want to detect mouse movements in Python.
The solution to this is very similar to that of using Pygame to intercept keyboard events (Recipe 11.11).
Open an editor (nano or IDLE) and paste in the following code. As with all the program examples in this book, you can also download the program from the Code section of the Raspberry Pi Cookbook website, where it is called mouse_pygame.py.
import pygame import sys from pygame.locals import * pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.mouse.set_visible(0) while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() if event.type == MOUSEMOTION: print(“Mouse: (%d, %d)” % event.pos) |
The MOUSEMOTION event is triggered whenever the mouse moves within the Pygame window. You can find the coordinates from the pos value of the event. The coordinates are absolute coordinates relative to the top-left corner of the window:
Mouse: (262, 285) Mouse: (262, 283) Mouse: (262, 281) Mouse: (262, 280) Mouse: (262, 278) Mouse: (262, 274) Mouse: (262, 270) Mouse: (260, 261) Mouse: (258, 252) Mouse: (256, 241) Mouse: (254, 232) |
Discussion
Other events that you can intercept are MOUSEBUTTONDOWN and MOUSEBUTTONUP. These can be used to detect when the left mouse button has been pressed or released.
See Also
The Pygame documentation for mouse can be found at the Pygame website.
For information on intercepting keyboard events using Pygame, see Recipe 11.11.