Write a program where a blue rectangle (which represents a stamp) follows a user's mouse around. Your program should draw a rectangle on the screen centered around the mouse when the user clicks.

Stamp tool demo

Solution

"""
File: stamp_tool.py
-------------------
This program lets you move the mouse to move a "stamp" around the screen,
and wherever you click it "stamps" (adds a copy of the stamp shape) to that
location.
"""
from graphics import Canvas
STAMP_SIZE = 50
def main():
    canvas = Canvas()
    canvas.set_canvas_title("Stamp Tool")
    stamp_tool = draw_stamp(canvascanvas.get_mouse_x()canvas.get_mouse_y()'blue')
    while True:
        clicks = canvas.get_new_mouse_clicks()
        for click in clicks:
            draw_stamp(canvasclick.xclick.y'black')
        # stamp tool should be topmost
        canvas.raise_to_front(stamp_tool)
        center_stamp(canvasstamp_toolcanvas.get_mouse_x()canvas.get_mouse_y())
        canvas.update()
    canvas.mainloop()
def draw_stamp(canvasxycolor):
    """
    Draws a stamp (rect) of the given color centered around the given location.
    Returns the rectangle drawn.
    """
    rect = canvas.create_rectangle(x - STAMP_SIZE / 2y - STAMP_SIZE / 2,
                                   x + STAMP_SIZE / 2y + STAMP_SIZE / 2)
    canvas.set_color(rectcolor)
    return rect
def center_stamp(canvasstampxy):
    """
    Repositions the given stamp (rect) to be centered around the given location.
    """
    canvas.moveto(stampx - canvas.get_width(stamp) / 2y - canvas.get_height(stamp) / 2)
if __name__ == "__main__":
    main()
X