# easiest way to plot x,y graphically during run-time?

Scott David Daniels Scott.Daniels at Acm.Org
Wed Jun 3 22:29:35 CEST 2009

```Esmail wrote:
> ... Tk seems a bit more complex .. but I really don't know much about
> it and its interface with Python to make any sort of judgments as
> to which option would be better.

This should look pretty easy:

import Tkinter as tk

class Mover(object):
def __init__(self, canvas, tag_or_id):
self.canvas = canvas
self.ident = tag_or_id
self.x = self.y = 0

def start(self, event):
self.x = event.x
self.y = event.y

def move(self, event):
if event.x != self.x or event.y != self.y:
dx = event.x - self.x
dy = event.y - self.y
self.x = event.x
self.y = event.y
self.canvas.move(self.ident, dx, dy)

def setup(root=None):
if root is None:
root = tk.Tk()
root.geometry('400x400+5+5')  # experiment: -- place and size
canvas = tk.Canvas(root)
canvas.pack(expand=1, fill=tk.BOTH)
# ovals are x1, y1, x2, y2
a = canvas.create_oval((50, 100, 70, 140), fill='red')
b = canvas.create_oval((100, 200, 140, 290), fill='blue')
c = canvas.create_oval((300, 300, 390, 330), fill='green')

canvas.itemconfig(a, fill='#55AADD') # using internet colors
canvas.move(a, 5, 5) # move a down right 5 pixels
mover = [Mover(canvas, ident) for ident in (a, b, c)]
canvas.bind("<B1-Motion>", mover[0].move)
canvas.bind("<Button-1>", mover[0].start)
canvas.bind("<B2-Motion>", mover[1].move)
canvas.bind("<Button-2>", mover[1].start)
canvas.bind("<B3-Motion>", mover[2].move)
canvas.bind("<Button-3>", mover[2].start)
return canvas, mover

if __name__ == '__main__':
c, m = setup()
tk.mainloop()

If you want to experiment, use something like:
python -m idlelib.idle -n
or
\$ python <wherever python is>/Lib/idlelib/idle.py -n
or
C:\> C:\Python25\python C:\Python25\Lib\idlelib\idle.py -n

To get an idle window with the -n switch on (so you are using the idle
"in-process") to see the effects of each Tkinter operation as you go.
You can then run these operations in place, seeing results and effects.

--Scott David Daniels
Scott.Daniels at Acm.Org

```