Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_mouse_rectangle_draw.py
- from PIL import Image, ImageTk
- from Tkinter import *
- root=Tk()
- canvas = Canvas(root)
- canvas.pack()
- def on_button_press(event):
- global start_x, start_y, rect
- # save mouse drag start position
- start_x = canvas.canvasx(event.x)
- start_y = canvas.canvasy(event.y)
- # create rectangle if not yet exist
- if not rect:
- rect = canvas.create_rectangle(x, y, 1, 1, outline='red')
- def on_move_press(event):
- global start_x, start_y, curX, curY, rect
- curX = canvas.canvasx(event.x)
- curY = canvas.canvasy(event.y)
- # expand rectangle as you drag the mouse
- canvas.coords(rect, start_x, start_y, curX, curY)
- def on_button_release(event):
- global start_x, start_y, curX, curY, rect
- try:
- canvas.create_rectangle(start_x, start_y, curX, curY, fill='green')
- except: pass
- rect = None
- x = y = 0
- canvas.grid(row=0,column=0,sticky=N+S+E+W)
- canvas.bind("<ButtonPress-1>", on_button_press)
- canvas.bind("<B1-Motion>", on_move_press)
- canvas.bind("<ButtonRelease-1>", on_button_release)
- rect = None
- start_x = None
- start_y = None
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement