Code for second python lab

lab2.py  [download]

# Based on draw3.py example

# Weird import for compatibility across Python 2 and Python 3
try:   
	import tkinter   
except ImportError:
	import Tkinter as tkinter   

############################################################
# PLANE CLASS
############################################################

class Plane ():
	def __init__(self, x, y, dx, dy):
		# Stash args as ivars
		self._x = x
		self._y = y
		self._dx = dx
		self._dy = dy

		# Make our graphical object
		# NB self._shape is just an ID number not an object
		# so we HAVE a shape, not we ARE a shape
		self._shape = canvas.create_rectangle (
			self._x, self._y,
			self._x + 30, self._y + 20,
			fill="blue")

		# Bind callback
		canvas.tag_bind (self._shape, '<Button-1>', self._onclick)

	# Mouse callback for this particular plane
	def _onclick (self, event):
		# Change its color to black
		canvas.itemconfigure (self._shape, fill="black")

############################################################
# MAIN PROGRAM 
############################################################

# Main window
top = tkinter.Tk()

# Canvas, in a global variable
canvas = tkinter.Canvas (top, height=400, width=400, background = "grey")
canvas.pack (fill="both", expand=1)

# Create some planes in the map and remember them in a list
planes = list()
planes.append (Plane (30, 20, 1, 2))
planes.append (Plane (100, 20, 2, 1))
planes.append (Plane (140, 40, 1, 1))

# Control panel area
controlPanel = tkinter.Frame (top, borderwidth=2, background="lightblue")
controlPanel.pack (side="top")

# Buttons in controlPanel
def b1Callback ():
	print (b1["text"] + " was pushed")
b1 = tkinter.Button (controlPanel)
b1["text"] = "Push me"
b1["command"] = b1Callback
b1.pack(side="left")

def b2Callback ():
	print (b2["text"] + " was pushed")
b2 = tkinter.Button (controlPanel)
b2["text"] = "Push me also"
b2["command"] = b2Callback
b2.pack(side="left")

top.mainloop()