Python Turtle Graphics
Module to add graphics to the screen.
Importing turtle
from turtle import #somethingKeep the white screen open
from turtle import Screen
screen = Screen()
screen.exit_on_click()Turtle Documentation. Turtle depends on Tkinter. Colour — TK (short for TkInter). Tkinter allows you to make a GUI (graphical user interface) which is what we have now — point and click instead of typing commands.
Color function
timmy = Turtle()
# option A
turtle.colormode(255)
timmy.color(243, 21, 53)
# option B
turtle.colormode(1.0)
timmy.color(0.5, 0.4, 0.8)setheading
turtle.setheading(0)
# 0 is East
# 90 is North
# 180 is West
# 270 is SouthEvent listeners (onkey)
def move_forward():
turtle.forward(10)
screen = Screen()
screen.listen()
screen.onkey("space", move_forward)
# onkey(the keybind, the function to execute)Instances and states
timmy = Turtle()
tommy = Turtle()
# both timmy and tommy are different instances.
# they can have different attributes and do different things.
timmy.color = "Green"
tommy.color = "Red"
# state of timmy's color attribute is different compared to tommy'sTurtle(shape=___)
timmy = Turtle(shape="turtle")
# there's an init function for shape
# turtle shape is 40 by 40 pxlsturtle.goto
timmy = Turtle()
timmy.goto(x, y)tracer()
Turns the turtle animation on/off. Unless we call update, the screen is not going to refresh.
# turn off
screen.tracer(0)
# update with 0.1s delay
screen.update()
time.sleep(0.1)
# turn onDefault size
Circle: 20px by 20px.
distance()
apple.distance(banana)
# measures the distance between the apple object and the banana objectturtle.write()
turtle.write("Hello!", align="center", font=("arial", 24, "normal"))See next
- Python-Projects — the Pong game uses turtle for paddle/ball movement