Advertisement
here2share

# Tk_MouseMover.py

Oct 18th, 2020
2,035
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. # Tk_MouseMover.py
  2.  
  3. from Tkinter import *
  4. root = Tk()
  5. canvas = Canvas(root, width=400, height=200)
  6. canvas.pack()
  7. canvas.create_oval(10, 10, 110, 60, fill="grey")
  8. canvas.create_text(60, 35, text="Oval")
  9. canvas.create_rectangle(10, 100, 110, 150, outline="blue")
  10. canvas.create_text(60, 125, text="Rectangle")
  11. canvas.create_line(60, 60, 60, 100, width=3)
  12.  
  13.  
  14. class MouseMover():
  15.   def __init__(self):
  16.     self.item = 0; self.previous = (0, 0)
  17.   def select(self, event):
  18.     widget = event.widget                       # Get handle to canvas
  19.     # Convert screen coordinates to canvas coordinates
  20.     xc = widget.canvasx(event.x); yc = widget.canvasx(event.y)
  21.     self.item = widget.find_closest(xc, yc)[0]        # ID for closest
  22.     self.previous = (xc, yc)
  23.     print((xc, yc, self.item))
  24.   def drag(self, event):
  25.     widget = event.widget
  26.     xc = widget.canvasx(event.x); yc = widget.canvasx(event.y)
  27.     canvas.move(self.item, xc-self.previous[0], yc-self.previous[1])
  28.     self.previous = (xc, yc)
  29.  
  30.  
  31. # Get an instance of the MouseMover object
  32. mm = MouseMover()
  33.  
  34. # Bind mouse events to methods (could also be in the constructor)
  35. canvas.bind("<Button-1>", mm.select)
  36. canvas.bind("<B1-Motion>", mm.drag)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement