## Being Animated

In the last tutorial we looked at the Canvas widget from Tkinter and we also had a look at the concept of cartesian coordinate systems. In our example we could identify specific pixels by counting across and down from the top left of the canvas (ordinarily cartesian systems count left and up).  We also bound the motion event to the canvas and used it to display the current coordinates of the mouse in the canvas.  The reason we did this is because to draw anything on the canvas you need to know the coordinates of where it is to be drawn.

Part of the homework was to identify what it was about the readout which didn’t make sense.   I didn’t see any comments on the tutorial, so I assume you’re baffled by what didn’t make sense.

Answer: if you move the mouse around enough, you can get pixel positions of (0,0) and (101,101).  This means that there are 102 pixels (from 1 to 100 is 100 plus one for each of 0 and 101 gives 102).  This is odd because when we set up the program we specifically said we wanted both the height and width to be 100 pixels.   Where are these two extra pixels in each direction coming from?  If you have a screen magnifier you can see it yourself, but you can also see it on the enlarged picture from the previous tutorial.  There is a white border around the blue canvas area:

It is this border where the extra pixels come from.

The canvas widget has a variety of methods for drawing stuff on the canvas area.  To use these methods you need to provide start and end coordinates.  Here is a yellow line drawn in the centre of the canvas from top to bottom:

```    start = (50,0)
end = (50,100)
self.canvas.create_line(start, end, fill = "yellow")```

to the earlier code after the self.canvas.bind line.  The thing to note here is the use of the coordinate system we discussed.

Exercise 1: swap the values of start and end.  What difference does this make?  Keep end static and try some different combinations for start.  Try to predict what it will look like before you run the program.

Exercise 2: change the code so that the line runs left to right through the middle rather than up and down.

Our next task is to try to animate this line.  We already have code to track mouse movements over the canvas, so let’s repurpose it to draw a line where the mouse pointer is (removing the code for the line in the middle):

```# -*- coding: utf-8 -*-
# canvasLine2.py
from Tkinter import *

formatString = "x: %03d, y: %03d"

class Canvassing():
def __init__(self, parent = None):
self.canvas = Canvas(width=100,height=100, bg = "blue")
self.canvas.pack()
self.readout = Label(text="This is a label")
self.canvas.bind("<Motion>",self.updateCoordinates)

def updateCoordinates(self,event):
start = (event.x, 0)
end = (event.x, 100)
self.canvas.create_line(start, end, fill = "yellow")

Canvassing()
mainloop()
```

If you run this and move the mouse around you will see something like this:

What’s going on here is that we are drawing new lines, but we aren’t erasing the old ones.  The computer, being “incredibly fast, accurate and stupid” doesn’t realise that we’re only interested in having one of the lines we’ve drawn present at any one time. We could recycle a single line moving it around, but that would require me to explain the concept of deltas and offsets, which you’ll need to look up for yourself.  Instead, we’re going to delete each line and draw a new one each time the mouse is moved.

```# -*- coding: utf-8 -*-
#canvasLine2B.py
from Tkinter import *

formatString = "x: %03d, y: %03d"

class Canvassing():
def __init__(self, parent = None):
self.canvas = Canvas(width=100,height=100, bg = "blue")
self.canvas.pack()
self.readout = Label(text="This is a label")
self.canvas.bind("<Motion>",self.updateCoordinates)
self.line = None

def updateCoordinates(self,event):  # really should rename this as we're doing something different now
start = (event.x, 0)
end = (event.x, 100)
self.canvas.delete(self.line) # first time through this will be None
# but Tkinter is ok with that
self.line = self.canvas.create_line(start, end, fill = "yellow")

Canvassing()
mainloop()

```

Now when you run the code you should get a single vertical line which follows your mouse pointer as it moves over the canvas.  Hey presto! You’ve just done your first animation.  Animation on computers involves deleting stuff one the screen which is out of date (or “painting” over it) and then replacing it with new stuff.  The value of self.line here is just an integer.  This is a reference that Tkinter uses to identify the objects it has drawn on the screen.

Exercise: add a print statement to print out the value of self.line for each call to updateCoordinates()

Exercise: change the code so that instead of a vertical line there is a cross hair (with a horizontal line running across the canvas) following the mouse pointer.  Hint: you need to draw two lines

Extra points: make the cross hair only 21 pixels wide centred on the mouse pointer.

Extra extra points: why 21 pixels and not 20?

## Canvassing

In this tutorial we are going to have a look at a new Tkinter widget called the Canvas.  A canvas widget, is, somewhat like a real canvas, something that you can throw paint or other stuff all over.  If you want to program games or animation you need to have an understanding of coordinate systems and computer animation.  A basic understanding of coordinates is the main aim of this tutorial.  In the process we will also incidentally cover another type of event – Exercise – find the new event. What is it called?

For this tutorial I want you to create a new file in your python4kids directory called canvassing.py

```# -*- coding: utf-8 -*-
from Tkinter import *

class Canvassing():
def __init__(self, parent = None):
self.canvas = Canvas(width=300, height=200, bg = "blue")
self.canvas.pack()

Canvassing()
mainloop()
```

This code, when run, should give you something that looks like this (click the close widget to close):

The default background is a sort of white, and I thought you might not be able to tell against the WordPress site, so I used blue instead.  Isn’t Python clever to know what blue is?  I hope you can also tell that if you put different numbers in for width and height you’d get a different looking rectangle.

Exercise: Change the height or width parameters (but not both) and see what you get, try a couple of different values.  Now try changing both the height and width parameters.

It’s important that you do the exercise as it demonstrates a relationship between the numbers and the size of the grid.  In our example, we have a rectangle which is wider (300) than it is tall (200).  In fact, if you were to look closely and count carefully, you would find that there are literally 300 blue dots along the bottom of the rectangle and 200 blue dots running up each side.

Exercise: Change width to be 10 and the height to be 1:

`    self.canvas = Canvas(width=10,height=1, bg = "blue")`

now, go find a magnifying glass and count the dots in the canvas.

Each of those dots is called a pixel (short for picture element).  Our original canvas was 300 pixels wide and 200 pixels high.  It had a total of 60,000 (ie 300×200) individual pixels!  Computers display their information by changing each of those individual pixels. Now, let’s make another tiny canvas and draw two tiny (1 pixel wide) lines on our new tiny canvas (save this to canvassing10x2.py):

```# -*- coding: utf-8 -*-
from Tkinter import *

class Canvassing():
def __init__(self, parent = None):
self.canvas = Canvas(width=10,height=2, bg = "blue")
self.canvas.pack()
self.canvas.create_line(1,1,2,1,fill="red")
self.canvas.create_line(5,2,6,2,fill="yellow")

Canvassing()
mainloop()
```

This should give you a window that looks something like this (grab an edge and expand it to get a close widget):

With this you should just about be able to see the two pixels we coloured in (don’t do this generally by the way, Tkinter is not built for doing pixel operations).  The first is the red pixel in the top left corner.  The second is the yellow pixel on the bottom in the middle.  In case you don’t have a magnifying glass, here’s a photo I took of my screen which shows it a little better:

The pixel boundaries are obvious in this photo (see the grid lines?).  If you look hard you can count the pixels (the photo is a little too good because it shows the subpixel array* used by my monitor to create the colours). For good measure here is the original picture blown up 4x:

So, why is the red in the top left and the yellow in the bottom middle?  Well, the canvas is  10 pixels wide and is 2 pixels high. So you can identify each of the pixels by whether they’re on the top row or bottom row, and how far along they are.  In this case, we created a red line starting at 1,1 and ending at 2, 1.  In each case the first number is how far along from the left and the second number is how far down from the top.  So 1,1 is the first pixel on the first line while 2,1 is pixel two on line 1 (if you look closely we’ve actually ended up with a black pixel at pixel 2.

In the second case (5,2,6,2) we drew a line from pixel 5 on line 2 (5,2) to pixel 6 on line 2 (6,2).  Since 5 is midway between 1 and 10 it looks like it’s in the middle.

So, what’s all this about?  Well anything to do with manipulating a canvas is about coordinates. That is, what pixel on what line.  Larger canvases just mean more pixels to play with.  Here we had 20 pixels (ten pixels each line on two lines) but our original example had 60,000.  A computer screen with a resolution of 1024 x 768 (which, as at June 2012, Wikipedia alleges represents about 20% of web users) has three quarters of a million pixels (786,432).   The bottom line is that if you understand how coordinates work, then you’re already a good way there to doing computer graphics and animations.

In the last example we use an event to print out the coordinates of the mouse as you move it around the canvas (save this to canvassingCoordinates.py):

```# -*- coding: utf-8 -*-
from Tkinter import *

formatString = "x: %03d, y: %03d"

class Canvassing():
def __init__(self, parent = None):
self.canvas = Canvas(width=100,height=100, bg = "blue")
self.canvas.pack()
self.readout = Label(text="This is a label")
self.canvas.bind("<Motion>",self.updateCoordinates)

def updateCoordinates(self,event):