1from Tkinter import *
2
3# this file demonstrates a more sophisticated movement --
4# move dots or create new ones if you click outside the dots
5
6class Test(Frame):
7    ###################################################################
8    ###### Event callbacks for THE CANVAS (not the stuff drawn on it)
9    ###################################################################
10    def mouseDown(self, event):
11        # see if we're inside a dot. If we are, it
12        # gets tagged as CURRENT for free by tk.
13        if not event.widget.find_withtag(CURRENT):
14            # there is no dot here, so we can make one,
15            # and bind some interesting behavior to it.
16            # ------
17            # create a dot, and mark it as CURRENT
18            fred = self.draw.create_oval(
19                event.x - 10, event.y -10, event.x +10, event.y + 10,
20                fill="green", tags=CURRENT)
21
22            self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
23            self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
24
25        self.lastx = event.x
26        self.lasty = event.y
27
28    def mouseMove(self, event):
29        self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
30        self.lastx = event.x
31        self.lasty = event.y
32
33    ###################################################################
34    ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
35    ###################################################################
36    def mouseEnter(self, event):
37        # the CURRENT tag is applied to the object the cursor is over.
38        # this happens automatically.
39        self.draw.itemconfig(CURRENT, fill="red")
40
41    def mouseLeave(self, event):
42        # the CURRENT tag is applied to the object the cursor is over.
43        # this happens automatically.
44        self.draw.itemconfig(CURRENT, fill="blue")
45
46    def createWidgets(self):
47        self.QUIT = Button(self, text='QUIT', foreground='red',
48                           command=self.quit)
49        self.QUIT.pack(side=LEFT, fill=BOTH)
50        self.draw = Canvas(self, width="5i", height="5i")
51        self.draw.pack(side=LEFT)
52
53        Widget.bind(self.draw, "<1>", self.mouseDown)
54        Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
55
56    def __init__(self, master=None):
57        Frame.__init__(self, master)
58        Pack.config(self)
59        self.createWidgets()
60
61test = Test()
62test.mainloop()
63