Advertisement
here2share

# Tk_mouse_rectangle_draw.py

Jun 14th, 2015
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. # Tk_mouse_rectangle_draw.py
  2.  
  3. from PIL import Image, ImageTk
  4. from Tkinter import *  
  5.  
  6. root=Tk()
  7. canvas = Canvas(root)
  8. canvas.pack()
  9.  
  10. def on_button_press(event):
  11.     global start_x, start_y, rect
  12.     # save mouse drag start position
  13.     start_x = canvas.canvasx(event.x)
  14.     start_y = canvas.canvasy(event.y)
  15.  
  16.     # create rectangle if not yet exist
  17.     if not rect:
  18.         rect = canvas.create_rectangle(x, y, 1, 1, outline='red')
  19.  
  20. def on_move_press(event):
  21.     global start_x, start_y, curX, curY, rect
  22.     curX = canvas.canvasx(event.x)
  23.     curY = canvas.canvasy(event.y)
  24.  
  25.     # expand rectangle as you drag the mouse
  26.     canvas.coords(rect, start_x, start_y, curX, curY)
  27.  
  28. def on_button_release(event):
  29.     global start_x, start_y, curX, curY, rect
  30.     try:
  31.         canvas.create_rectangle(start_x, start_y, curX, curY, fill='green')
  32.     except: pass
  33.     rect = None
  34.  
  35. x = y = 0
  36.  
  37. canvas.grid(row=0,column=0,sticky=N+S+E+W)
  38.  
  39. canvas.bind("<ButtonPress-1>", on_button_press)
  40. canvas.bind("<B1-Motion>", on_move_press)
  41. canvas.bind("<ButtonRelease-1>", on_button_release)
  42.  
  43. rect = None
  44.  
  45. start_x = None
  46. start_y = None
  47.  
  48. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement