Python exercises for ages 10+

Create a paint app

Part 1

Using the below code as a starting point, create a small square wherever the user drags their mouse.

from tkinter import *

c = Canvas(Tk(), width = 500, height = 500)
c.pack()

def onMouseClicked(event):
    x = event.x
    y = event.y
    print("Mouse clicked at:", x, y)

def onMouseDragged(event):
    x = event.x
    y = event.y
    print("Mouse dragged at:", x, y)

c.bind("<Button-1>", onMouseClicked)
c.bind("<B1-Motion>", onMouseDragged)

mainloop()

Part 2

Calculate the coordinates and create three squares in a row (red, green, and blue) at the bottom left corner of the window like in the image below.

The paint window

Extend the mouse-click callback function to detect if a mouse click is inside the bounds of one of these three squares. If it is, set a global colour variable to the corresponding colour and use it to change the colour of your “brush”. Set the named variable outline to the same colour as fill to avoid black outlines.

Extra

A visualisation of points inside and outside an axis-aligned bounding box