# Developers Planet

### How do I work with the geometry of Tkinter in Python?

I've been having trouble wrapping my head around the geometry of Tkinter. I have a range of questions that I was hoping someone would be kind enough to clear up for me.

When making the rectangle in the below code I passed in 4 parameters. I'm aware that they're an x1, y1, x2, y2 parameter but how exactly does this work? I can't seem to create a rectangle of a specific size and place it exactly where I want. Also, what does the 20+20 thing mean in the 3rd and fourth parameter exactly?

How do I detect a specific coordinate? I would like to be able to detect the line on the screen and execute code based when the rectangle touches it but I'm clueless. I also can't position the line in the position I would want to either to emphasize how little I get Tkinter's geometry.

``````window = Tk()
window.geometry("400x200+450+300")

canvas1 = Canvas(window, width = 600, height = 300, bg='white')
canvas1.pack()
canvas1.create_line(25, 50, 50, 50)

robot = canvas1.create_rectangle(10, 10, 20+20, 20+20)

x1, y1, x2, y2 = canvas1.coords(robot)

def right(event):
x1, y1, x2, y2 = canvas1.coords(robot)
canvas1.coords(robot, x1+10, y1, x2+10, y2)

def left(event):
x1, y1, x2, y2 = canvas1.coords(robot)
canvas1.coords(robot, x1-10, y1, x2-10, y2)

def up(event):
x1, y1, x2, y2 = canvas1.coords(robot)
canvas1.coords(robot, x1, y1-10, x2, y2-10)

def down(event):
x1, y1, x2, y2 = canvas1.coords(robot)
canvas1.coords(robot, x1, y1+10, x2, y2+10)

canvas1.focus_set()
canvas1.bind("<Right>", right)
canvas1.bind("<Left>", left)
canvas1.bind("<Up>", up)
canvas1.bind("<Down>", down)
``````

Thanks for any help.

Bryan Oakley February 2016

Tkinter canvas coordinates start with 0,0 at the upper left corner of the canvas. As X gets bigger the point moves to the right. As Y gets bigger the point moves down.

Consider this line of code:

``````robot = canvas1.create_rectangle(10, 10, 20+20, 20+20)
``````

This creates a rectangle formed by the coordinates (10,10) and (40,40). Starting from the upper left corner, tkinter will count ten pixels over and ten pixels down to draw the first corner of the rectangle. The opposite corner of the rectangle is (40,22). It will look like this (not to scale):

``````  point 1 (10,10)
+

+
point 2 (40, 40)
``````

Tkinter will then create a rectangle by computing the missing corners wich are at (40,10) and (10,22)

``````  point 1 (10,10)
+--------------+
|              |
|              |
+--------------+
point 2 (40,40)
``````

As for the second question (which really should be a separate question), you can determine if one object overlaps another with the canvas find_overlapping method.