/Demo/tkinter/matt/rubber-line-demo-1.py

http://unladen-swallow.googlecode.com/ · Python · 51 lines · 33 code · 10 blank · 8 comment · 2 complexity · bff5b0f70d765a3410ce3ea27f5d7f3f MD5 · raw file

  1. from Tkinter import *
  2. class Test(Frame):
  3. def printit(self):
  4. print "hi"
  5. def createWidgets(self):
  6. self.QUIT = Button(self, text='QUIT',
  7. background='red',
  8. foreground='white',
  9. height=3,
  10. command=self.quit)
  11. self.QUIT.pack(side=BOTTOM, fill=BOTH)
  12. self.canvasObject = Canvas(self, width="5i", height="5i")
  13. self.canvasObject.pack(side=LEFT)
  14. def mouseDown(self, event):
  15. # canvas x and y take the screen coords from the event and translate
  16. # them into the coordinate system of the canvas object
  17. self.startx = self.canvasObject.canvasx(event.x)
  18. self.starty = self.canvasObject.canvasy(event.y)
  19. def mouseMotion(self, event):
  20. # canvas x and y take the screen coords from the event and translate
  21. # them into the coordinate system of the canvas object
  22. x = self.canvasObject.canvasx(event.x)
  23. y = self.canvasObject.canvasy(event.y)
  24. if (self.startx != event.x) and (self.starty != event.y) :
  25. self.canvasObject.delete(self.rubberbandLine)
  26. self.rubberbandLine = self.canvasObject.create_line(
  27. self.startx, self.starty, x, y)
  28. # this flushes the output, making sure that
  29. # the rectangle makes it to the screen
  30. # before the next event is handled
  31. self.update_idletasks()
  32. def __init__(self, master=None):
  33. Frame.__init__(self, master)
  34. Pack.config(self)
  35. self.createWidgets()
  36. # this is a "tagOrId" for the rectangle we draw on the canvas
  37. self.rubberbandLine = None
  38. Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
  39. Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
  40. test = Test()
  41. test.mainloop()