Let us examine the main feature of the dragtest.py program: the DragSquare
# New object: a square that can be dragged around
def __init__(self, x1, y1, x2, y2, colour):
Square.__init__(self, x1, y1, x2, y2, colour)
self.old_colour = colour
self.dragging = 0
We have inherited features of the Square class, which provides a static square of
a particular colour at a specified place in a window's work area. Since the redrawing
method of this class will be the same as that for the Square class, we re-use its
code. We also set the attribute old_colour as this is the default colour for the
def click(self, x, y, buttons, window):
if buttons == app._select_drag_:
if x < self.x1: return 0
if y < self.y1: return 0
if x > self.x2: return 0
if y > self.y2: return 0
The click method is called when the app module recieves a click event from the window
manager. The x and y coordinates of the position in the window where the click occurred are
given in work area coordinates so that, after we have checked that the select button is being
held down for a dragging operation, we can determine whether the click occurred within the
object's bounding box. If it missed then we return 0.
# Start a drag operation in only one of the parents
app.windows[window].start_drag(self.name, x, y)
self.colour = 11
self.dragging = 1
In this block, we respond if the click was inside the object's bounding box. The parent
window, the handle of which is passed as window is informed that this object is to
be dragged within the window. The colour of the square is changed to red (desktop colour 11),
we record that this object is being dragged (self.dragging = 1) and we claim this
click by returning -1.
elif buttons == 0 and self.dragging == 1:
self.dragging = 0
self.colour = self.old_colour
for parent in self.parents:
app.windows[parent].update(self.x1, self.y1, self.x2+1, self.y2+1)
If the mouse buttons are all depressed (up) and the object is being dragged then we record that
this object is no longer being dragged (self.dragging = 0), give it its old colour,
and redraw the square in all the parent windows so that appears with this old colour.
If any other buttons were pressed then we ignore the event and return 0.
A lot of the work required for moving objects in this manner is performed in the library.