Freehand Drawing

A simple freehand drawing program allows the user to draw line segments by dragging the mouse on a canvas.  The user can clear the drawing from the canvas by clicking a command button.  Here is the interface for this program:

 

 

This program makes use of a single canvas.  The canvas includes the mousePressed and mouseMoved methods.  When the user presses the mouse, the mousePressed method saves the mouse coordinates in a pair of instance variables.  When the user then drags the mouse to a new location, the mouseMoved method draws a line segment from the saved coordinates to the new mouse location, updates the saved coordinates to that new location, and saves the ID of the line segment just drawn.

Here is the code for the complete program (canvasdemo3.py):

 

 

from breezypythongui import EasyFrame, EasyCanvas

 

class CanvasDemo(EasyFrame):

    """Supports freehand drawing with the mouse."""

 

    def __init__(self):

        """Sets up the window and widgets."""

        EasyFrame.__init__(self, title = "Freehand Drawing")

 

        # The canvas

        self.canvas = self.addCanvas(canvas = Sketchpad(self),

                                     row = 0, column = 0)

       

        # The command button

        self.button = self.addButton(text = "Clear Shapes",

                                     row = 1, column = 0,

                                     command = self.clearAll)

 

    def clearAll(self):

        """Deletes all drawings from the canvas."""

        self.canvas.clearAll()

 

 

class Sketchpad(EasyCanvas):

    """This canvas supports Supports freehand drawing with the mouse."""

 

    def __init__(self, parent):

        """Background is gray.  Items drawn are tracked for later erasing."""

        EasyCanvas.__init__(self, parent, background = "gray")

        self.items = list()

 

    def mousePressed(self, event):

        """Sets the first endpoint of a line segment."""

        self.x = event.x

        self.y = event.y

 

    def mouseMoved(self, event):

        """Sets the second end point of a line segment.

        Draws the line segment in blue and saves its id."""

        if self.x != event.x and self.y != event.y:

            item = self.drawLine(self.x, self.y,

                                 event.x, event.y,

                                 width = 3, fill = "#0000CC")

            self.x = event.x

            self.y = event.y

            self.items.append(item)

 

    def clearAll(self):

        """Deletes all drawings from the canvas."""

        for item in self._items:

            self.deleteItem(item)

        self.items = list()

 

 

# Instantiate and pop up the window.

CanvasDemo().mainloop()

 

 

A simple extension would be to add dropdown menus for pen colors and pen widths.