/Demo/tkinter/matt/canvas-moving-or-creating.py

http://unladen-swallow.googlecode.com/ · Python · 62 lines · 33 code · 11 blank · 18 comment · 1 complexity · bc6e2257019ff8c8f2d33f4ca51467d9 MD5 · raw file

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