Book Graphics
# triangle.pyw
# Interactive graphics program to draw a triangle
from graphics import *
def main():
win = GraphWin("Draw a Triangle")
win.setCoords(0.0, 0.0, 10.0, 10.0)
message = Text(Point(5, 0.5), "Click on three points")
message.draw(win)
# Get and draw three vertices of triangle
p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
p2.draw(win)
p3 = win.getMouse()
p3.draw(win)
# Use Polygon object to draw the triangle
triangle = Polygon(p1,p2,p3)
triangle.setFill("peachpuff")
triangle.setOutline("cyan")
triangle.draw(win)
# Wait for another click to exit
message.setText("Click anywhere to quit.")
win.getMouse()
main()
# convert_gui.pyw
# Program to convert Celsius to Fahrenheit using a simple
# graphical interface.
from graphics import *
def main():
win = GraphWin("Celsius Converter", 300, 200)
win.setCoords(0.0, 0.0, 3.0, 4.0)
# Draw the interface
Text(Point(1,3), " Celsius Temperature:").draw(win)
Text(Point(1,1), "Fahrenheit Temperature:").draw(win)
input = Entry(Point(2,3), 5)
input.setText("0.0")
input.draw(win)
output = Text(Point(2,1),"")
output.draw(win)
button = Text(Point(1.5,2.0),"Convert It")
button.draw(win)
Rectangle(Point(1,1.5), Point(2,2.5)).draw(win)
# wait for a mouse click
win.getMouse()
# convert input
celsius = eval(input.getText())
fahrenheit = 9.0/5.0 * celsius + 32
# display output and change button
output.setText("%0.1f" % fahrenheit)
button.setText("Quit")
# wait for click and then quit
win.getMouse()
win.close()
main()
# addinterest1.py
# Program illustrates failed attempt to change value of a parameter
def addInterest(balance, rate):
newBalance = balance * (1+rate)
balance = newBalance
def test():
amount = 1000
rate = 0.05
addInterest(amount, rate)
print amount
test()
# addinterest2.py
# Illustrates use of return to change value in calling program.
def addInterest(balance, rate):
newBalance = balance * (1+rate)
return newBalance
def test():
amount = 1000
rate = 0.05
amount = addInterest(amount, rate)
print amount
test()
# addinterest3.py
# Illustrates modification of a mutable parameter (a list).
def addInterest(balances, rate):
for i in range(len(balances)):
balances[i] = balances[i] * (1+rate)
def test():
amounts = [1000, 2200, 800, 360]
rate = 0.05
addInterest(amounts, 0.05)
print amounts
test()