from __future__ import print_function try: import Tkinter except ImportError: import tkinter as Tkinter # # Create a GUI with a canvas where the user can draw # lines using the mouse. # class CanvasDemo: # __init__() and run() together serve the same # purpose as the main() function in other examples. def __init__(self): self.x = 0 self.y = 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 def make_ui(self, app): b = Tkinter.Button(app, text="Clear", command=self.clear) b.grid(row=1, column=0, sticky="ew") 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") # When button is pressed, execute self.on_select c.bind("", self.on_select) # When button is released, execute self.on_release c.bind("", self.on_release) self.handler = None self.canvas = c # "clear" is called when the user presses the "Clear" # button. We clear the canvas of all the lines we # created by deleting all items marked with tag "line". def clear(self): self.canvas.delete("line") # "on_select", "on_drag" and "on_release" are event # handlers that get called when the mouse button is # pressed down, dragged and released, respectively. # On press, we record the mouse position and bind to # mouse motion=drag. On drag, we add a line from the # previous position to the current position, and record # the current position. On release, we add a line from # the previous position and unbind from mouse motion. def on_select(self, event): self.x = event.x self.y = event.y self.handler = self.canvas.bind("", self.on_drag) def on_drag(self, event): self.canvas.create_line(self.x, self.y, event.x, event.y, fill="black", tags="line") self.x = event.x self.y = event.y def on_release(self, event): self.canvas.create_line(self.x, self.y, event.x, event.y, fill="black", tags="line") self.canvas.unbind("", self.handler) self.handler = None if __name__ == "__main__": CanvasDemo().run() print("Finished")