from __future__ import print_function try: import Tkinter except ImportError: import tkinter as Tkinter # # Create a GUI with a canvas whose items may be moved # using the mouse. # class CanvasDemo: # __init__() and run() together serve the same # purpose as the main() function in other examples. def __init__(self): self.moving_item = None self.orig_color = None self.dragx = 0 self.dragy = 0 self.app = Tkinter.Frame() self.app.grid(sticky="nsew") self.make_ui(self.app) top = self.app.winfo_toplevel() top.columnconfigure(0, weight=1) top.rowconfigure(0, weight=1) def run(self): self.app.mainloop() # "make_ui" is similar to the one in tkinter_canvas.py # except we call "make_movable" for each item we create. def make_ui(self, app): c = Tkinter.Canvas(app, width=400, height=400, bg="cyan") app.columnconfigure(0, weight=1) app.rowconfigure(0, weight=1) c.grid(row=0, column=0, sticky="nsew") r = c.create_rectangle((10, 10, 20, 30), fill="green") self.make_movable(c, r) r2 = c.create_oval((100, 100, 300, 200), fill="blue") self.make_movable(c, r2) # "make_movable" simply registers callback functions for # when the user presses down on button 1 (usually the left # button), moves the mouse while button 1 is down, or # releases button 1. All three callbacks are methods # of our class. When the button is pressed, we record # which item the mouse was over, so subsequent drag and # release actions may be applied to the correct item. # To pass the extra argument on selection, we define # a local function with an "item" argument with a # default value of the item being registered. def make_movable(self, c, item): def on_select(event, self=self, c=c, item=item): self.on_select(event, c, item) c.tag_bind(item, "", on_select) c.tag_bind(item, "", self.on_drag) c.tag_bind(item, "", self.on_release) def on_select(self, event, c, item): self.moving_item = (c, item) self.orig_color = c.itemcget(item, "fill") self.dragx = event.x self.dragy = event.y c.itemconfigure(item, fill="yellow") def on_drag(self, event): dx = event.x - self.dragx dy = event.y - self.dragy self.dragx = event.x self.dragy = event.y c, item = self.moving_item c.move(item, dx, dy) def on_release(self, event): c, item = self.moving_item c.itemconfigure(item, fill=self.orig_color) self.moving_item = None if __name__ == "__main__": CanvasDemo().run() print("Finished")