draw3

draw3.py  [download]

# 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"] = "grey"
		self.bind('<Button-1>', self._myCallback)
		
		# Draw some items
		self.create_line (0, 50, 100, 50, fill="red") #//*1 Retained mode drawing
		self.create_line (100, 100, 200, 100, fill="red") #//*1
		self.create_rectangle (150, 150, 175, 175, fill="red") #//*1
		self.create_oval (50, 150, 75, 175, fill="red") #//*1

		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) #//*2 They do pick correlation
		y = canvas.canvasy(event.y) #//*2
		print ("Mouse down at " + str(x) + "," + str(y))

		# Find the nearest item and tweak it
		item = canvas.find_closest(x, y) #//*2
		if canvas.itemcget (item, "fill") == "red": #//*3 Change color if red
			canvas.itemconfigure (item, fill="blue") #//*3
		elif canvas.type (item) != None: #//*4 Else delete item
			print ("Deleting " + canvas.type (item)) #//*4
			canvas.delete (item) #//*4

# 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()