Hello, little turtles!
import turtle wn = turtle.Screen() wn.bgcolor("lightgreen") # Set the window background color wn.title("Hello, Tess!") # Set the window title tess = turtle.Turtle() tess.color("blue") # Tell tess to change her color tess.pensize(3) # Tell tess to set her pen width tess.forward(50) tess.left(120) tess.forward(50) wn.mainloop()
When we run this program, this new window pops up, and will remain on the screen until we close it.
from:http://www.openbookproject.net/thinkcs/python/english3e/hello_little_turtles.html
import turtle wn = turtle.Screen() # Set up the window and its attributes wn.bgcolor("lightgreen") wn.title("Tess & Alex") tess = turtle.Turtle() # Create tess and set some attributes tess.color("hotpink") tess.pensize(5) alex = turtle.Turtle() # Create alex tess.forward(80) # Make tess draw equilateral triangle tess.left(120) tess.forward(80) tess.left(120) tess.forward(80) tess.left(120) # Complete the triangle tess.right(180) # Turn tess around tess.forward(80) # Move her away from the origin alex.forward(50) # Make alex draw a square alex.left(90) alex.forward(50) alex.left(90) alex.forward(50) alex.left(90) alex.forward(50) alex.left(90) wn.mainloop()
A turtle can “stamp” its footprint onto the canvas, and this will remain after the turtle has moved somewhere else. Stamping works, even when the pen is up.
import turtle wn = turtle.Screen() wn.bgcolor("lightgreen") tess = turtle.Turtle() tess.shape("turtle") tess.color("blue") tess.penup() # This is new size = 20 for i in range(30): tess.stamp() # Leave an impression on the canvas size = size + 3 # Increase the size on every iteration tess.forward(size) # Move tess along tess.right(24) # ... and turn her wn.mainloop()
The turtle has a lot more power than we’ve seen so far. The full documentation can be found athttp://docs.python.org/py3k/library/turtle.htmlor within PyScripter, useHelpand search for the turtle module.
Here are a couple of new tricks for our turtles:
def draw_bar(t, height): """ Get turtle t to draw one bar, of height. """ t.begin_fill() # Added this line t.left(90) t.forward(height) t.write(" "+ str(height)) t.right(90) t.forward(40) t.right(90) t.forward(height) t.left(90) t.end_fill() # Added this line t.forward(10) wn = turtle.Screen() # Set up the window and its attributes wn.bgcolor("lightgreen") tess = turtle.Turtle() # Create tess and set some attributes tess.color("blue", "red") tess.pensize(3) xs = [48,117,200,240,160,260,220] for a in xs: draw_bar(tess, a) wn.mainloop()优质内容筛选与推荐>>