Question 11.12: Intercepting Mouse Movements You want to detect mouse moveme......

Intercepting Mouse Movements

You want to detect mouse movements in Python.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

Related Answered Questions

Question: 11.13

Verified Answer:

Use an RTC (real-time clock) module. A very common...
Question: 11.8

Verified Answer:

Keypads are arranged in rows and columns, with a p...
Question: 11.2

Verified Answer:

Record the last state of the button and invert tha...
Question: 11.1

Verified Answer:

Connect a switch to a GPIO pin and use the RPi.GPI...
Question: 11.7

Verified Answer:

Use a rotary (quadrature encoder) connected to two...
Question: 11.9

Verified Answer:

Use a PIR (passive infrared) motion detector modul...
Question: 11.11

Verified Answer:

There are at least two ways to solve this problem....
Question: 11.10

Verified Answer:

A 3.3V serial GPS module can be connected directly...