# Simple Canvas example # CS 1803 - Fall 2010 # Copyright, Jay Summet # from tkinter import * #We define a drawing class here: class Drawing(): lines = [] lastX = None lastY = None redLine = None #This is the constructor. It draws the window with the canvas. def __init__(self, tkMainWin): frame = Frame(tkMainWin) frame.pack() self.canvas = Canvas(frame) self.canvas.bind("",self.clicked) self.canvas.bind("",self.rightClicked) self.canvas.bind("",self.mouseMoved) self.canvas.pack() #This event handler (callback) will draw lines, saving their ID #in a list. def clicked(self, event): print("Button down!") if self.lastX != None: l = self.canvas.create_line(self.lastX,self.lastY,event.x,event.y) self.lines.append(l) self.lastX = event.x self.lastY = event.y pass #This handler deals with "right-click" events, which cause the #last line drawn to be deleted! def rightClicked(self,event): print("rightClicked!") self.lastX = None self.lastY = None if (len( self.lines) > 0): self.canvas.delete( self.lines[-1]) del self.lines[-1] #Need to keep our data structure in #sync with the canvas #Manage the red line! if self.redLine != None: self.canvas.delete(self.redLine) self.redLine = None #This handler deals with "mouse motion" events, and draws a red # "rubber-band" line illustrating where the next line will be # drawn if the user clicks now... def mouseMoved(self, event): print("Mouse Moved!") if self.lastX != None: if self.redLine != None: self.canvas.delete(self.redLine); self.redLine = self.canvas.create_line(self.lastX, self.lastY, event.x, event.y, fill="red") #This code starts up TK and creates a main window. mainWin = Tk() #This code creates an instance of the TTT object. ttt = Drawing( mainWin) #This line starts the main event handling loop and sets us on our way... mainWin.mainloop()