Advertisement
here2share

# Tk_mouse_draw_rectangles.py

Aug 8th, 2016
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. # Tk_mouse_draw_rectangles.py
  2.  
  3. import Tkinter as tk
  4. from PIL import Image, ImageTk
  5.  
  6. colorList = ["blue", "red", "green", "black", "yellow", "magenta", "orange"]
  7. def rnd_color():
  8.     colorList.append(colorList[0])
  9.     return colorList.pop(0)
  10. class ExampleApp(tk.Tk):
  11.     def __init__(self):
  12.         tk.Tk.__init__(self)
  13.         self.x = self.y = 0
  14.         self.canvas = tk.Canvas(self, width=512, height=512, cursor="cross")
  15.         self.canvas.pack(side="top", fill="both", expand=True)
  16.         self.canvas.bind("<ButtonPress-1>", self.on_button_press)
  17.         self.canvas.bind("<B1-Motion>", self.on_move_press)
  18.         self.canvas.bind("<ButtonRelease-1>", self.on_button_release)
  19.  
  20.         self.rect = None
  21.  
  22.         self.start_x = None
  23.         self.start_y = None
  24.  
  25.     def on_button_press(self, event):
  26.         # save mouse drag start position
  27.         self.start_x = event.x
  28.         self.start_y = event.y
  29.  
  30.         # create rectangle if not yet exist
  31.         #if not self.rect:
  32.         self.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, fill=rnd_color())
  33.  
  34.     def on_move_press(self, event):
  35.         curX, curY = (event.x, event.y)
  36.  
  37.         # expand rectangle as you drag the mouse
  38.         self.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY)
  39.  
  40.     def on_button_release(self, event):
  41.         pass
  42.  
  43. if __name__ == "__main__":
  44.     app = ExampleApp()
  45.     app.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement