# Like java Draw3, plus extra features # Weird import for compatibility across Python 2 and Python 3 try: import tkinter except ImportError: import Tkinter as tkinter class MyCanvas (tkinter.Canvas): def __init__(self, parent): tkinter.Canvas.__init__ (self, parent) # Set our stuff self["background"] = "light grey" self.bind('', self._myCallback) # Draw some items self.create_line (0, 50, 100, 50, fill="red") self.create_line (100, 100, 200, 100, fill="red") self.create_rectangle (150, 150, 175, 175, fill="red") self.create_oval (50, 150, 75, 175, fill="red") self.pack (fill="both", expand=1) def _myCallback (self, event): # Convert from window coordinates to canvas coordinates canvas = event.widget x = canvas.canvasx(event.x) y = canvas.canvasy(event.y) print ("Mouse down at " + str(x) + "," + str(y)) # Find the nearest item and tweak it item = canvas.find_closest(x, y) if canvas.itemcget (item, "fill") == "red": canvas.itemconfigure (item, fill="blue") elif canvas.type (item) != None: print ("Deleting " + canvas.type (item)) canvas.delete (item) # Same as in simplebutton3 class MyButton (tkinter.Button): def __init__(self, label, parent): tkinter.Button.__init__ (self, parent) self["text"] = label self["command"] = self._myCallback self.pack() def _myCallback (self): print (self["text"] + " was pushed") # Main program top = tkinter.Tk() b1 = MyButton ("Push me", top) b2 = MyButton ("Push me also", top) c = MyCanvas (top) top.mainloop()