/Demo/tkinter/matt/canvas-moving-w-mouse.py

http://unladen-swallow.googlecode.com/ · Python · 55 lines · 31 code · 11 blank · 13 comment · 0 complexity · 1d7e5aa626fbe11ee292e410e989a196 MD5 · raw file

  1. from Tkinter import *
  2. # this file demonstrates the movement of a single canvas item under mouse control
  3. class Test(Frame):
  4. ###################################################################
  5. ###### Event callbacks for THE CANVAS (not the stuff drawn on it)
  6. ###################################################################
  7. def mouseDown(self, event):
  8. # remember where the mouse went down
  9. self.lastx = event.x
  10. self.lasty = event.y
  11. def mouseMove(self, event):
  12. # whatever the mouse is over gets tagged as CURRENT for free by tk.
  13. self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
  14. self.lastx = event.x
  15. self.lasty = event.y
  16. ###################################################################
  17. ###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
  18. ###################################################################
  19. def mouseEnter(self, event):
  20. # the CURRENT tag is applied to the object the cursor is over.
  21. # this happens automatically.
  22. self.draw.itemconfig(CURRENT, fill="red")
  23. def mouseLeave(self, event):
  24. # the CURRENT tag is applied to the object the cursor is over.
  25. # this happens automatically.
  26. self.draw.itemconfig(CURRENT, fill="blue")
  27. def createWidgets(self):
  28. self.QUIT = Button(self, text='QUIT', foreground='red',
  29. command=self.quit)
  30. self.QUIT.pack(side=LEFT, fill=BOTH)
  31. self.draw = Canvas(self, width="5i", height="5i")
  32. self.draw.pack(side=LEFT)
  33. fred = self.draw.create_oval(0, 0, 20, 20,
  34. fill="green", tags="selected")
  35. self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
  36. self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
  37. Widget.bind(self.draw, "<1>", self.mouseDown)
  38. Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
  39. def __init__(self, master=None):
  40. Frame.__init__(self, master)
  41. Pack.config(self)
  42. self.createWidgets()
  43. test = Test()
  44. test.mainloop()