blob: 447e29021f2be4ae858e5156350d13946b00687a [file] [log] [blame]
Guido van Rossum35820f71994-10-07 09:55:26 +00001from Tkinter import *
2
3# this file demonstrates the movement of a single canvas item under mouse control
4
5class Test(Frame):
6 ###################################################################
7 ###### Event callbacks for THE CANVAS (not the stuff drawn on it)
8 ###################################################################
9 def mouseDown(self, event):
10 # remember where the mouse went down
11 self.lastx = event.x
12 self.lasty = event.y
Guido van Rossum89cb67b1996-07-30 18:57:18 +000013
Guido van Rossum35820f71994-10-07 09:55:26 +000014 def mouseMove(self, event):
Guido van Rossum89cb67b1996-07-30 18:57:18 +000015 # whatever the mouse is over gets tagged as CURRENT for free by tk.
16 self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
Guido van Rossum35820f71994-10-07 09:55:26 +000017 self.lastx = event.x
18 self.lasty = event.y
19
20 ###################################################################
21 ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
22 ###################################################################
23 def mouseEnter(self, event):
Guido van Rossum89cb67b1996-07-30 18:57:18 +000024 # the CURRENT tag is applied to the object the cursor is over.
Guido van Rossum35820f71994-10-07 09:55:26 +000025 # this happens automatically.
Guido van Rossum89cb67b1996-07-30 18:57:18 +000026 self.draw.itemconfig(CURRENT, fill="red")
Guido van Rossum35820f71994-10-07 09:55:26 +000027
28 def mouseLeave(self, event):
Guido van Rossum89cb67b1996-07-30 18:57:18 +000029 # the CURRENT tag is applied to the object the cursor is over.
Guido van Rossum35820f71994-10-07 09:55:26 +000030 # this happens automatically.
Guido van Rossum89cb67b1996-07-30 18:57:18 +000031 self.draw.itemconfig(CURRENT, fill="blue")
Guido van Rossum35820f71994-10-07 09:55:26 +000032
33 def createWidgets(self):
Guido van Rossum89cb67b1996-07-30 18:57:18 +000034 self.QUIT = Button(self, text='QUIT', foreground='red',
35 command=self.quit)
36 self.QUIT.pack(side=LEFT, fill=BOTH)
37 self.draw = Canvas(self, width="5i", height="5i")
38 self.draw.pack(side=LEFT)
Guido van Rossum35820f71994-10-07 09:55:26 +000039
40 fred = self.draw.create_oval(0, 0, 20, 20,
Guido van Rossum89cb67b1996-07-30 18:57:18 +000041 fill="green", tags="selected")
Guido van Rossum35820f71994-10-07 09:55:26 +000042
Guido van Rossumfaefe4c1996-05-24 18:40:46 +000043 self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
44 self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
Guido van Rossum35820f71994-10-07 09:55:26 +000045
46 Widget.bind(self.draw, "<1>", self.mouseDown)
47 Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
48
49 def __init__(self, master=None):
50 Frame.__init__(self, master)
51 Pack.config(self)
52 self.createWidgets()
53
54test = Test()
55test.mainloop()