How to Draw on the Turtle Canvas
We'll will draw a circle - our body - using the turtle.circle()
method of the Turtle object.
Animating a Body
To make the circle appear to move across the canvas, i.e., animate the circle, we'll
simply draw the circle repeatedly, changing its position
progressively.
Since the ball (circle) is the turtle itself, it does not any
clearing since it does not leave any traces.
Create 2 new files; File, New File.
Call them Facet.py and MovingBody.py.
Type out the adjoining Python / Turtle code for animating
an image body across the canvas component.
Note: The code module for our Facet class will remain the
same for the rest of the demonstrations in this category.
Hence it will be left out hence forth.
Important: When trying to click on the button to get things
started, you might need to click away from the button text.
Template class
import turtle
class Template:
def __init__(self):
screen = turtle.getscreen()
screen.title("usingMaths.com")
screen.setup(width=0.9, height=0.9, startx=None, starty=None)
screen.colormode(255)
self.bgcolour = "#cccccc"
screen.bgcolor(self.bgcolour)
screen.delay(0)
self.screen = screen
self.wnd_width = self.screen.window_width()
self.wnd_height = self.screen.window_height()
def controlButtons(self):
self.button = turtle.clone()
turtle.speed(0)
turtle.penup()
turtle.setposition(-self.wnd_width/2, self.wnd_height/2)
turtle.color("black", "pink")
turtle.pendown()
turtle.begin_fill()
turtle.forward(self.wnd_width)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(self.wnd_width)
turtle.right(90)
turtle.forward(50)
turtle.end_fill()
self.button.speed(0)
self.button.penup()
self.button.setposition(0, self.wnd_height/2 - 25)
self.button.shape("square")
self.button.resizemode("user")
self.button.shapesize(2, 8)
self.button.color("black", (255, 0, 255))
return turtle.getturtle()
Python code for MovingBody file
from Facet import Template
def prep():
global x_ball, y_ball
scene.button.onrelease(play)
screen.delay(20)
x_ball = 100 - scene.wnd_width/2; y_ball = 0
diameter = 5
ball_colour = "#ffff00"
turtle.penup()
turtle.setposition(scene.button.xcor(), scene.button.ycor()-10)
turtle.pendown()
turtle.write("Move", align="center", font=("Arial",16,"bold"))
turtle.penup()
turtle.setposition(x_ball, y_ball)
turtle.shape("circle")
turtle.shapesize(diameter, diameter)
turtle.color(ball_colour, ball_colour)
def play(x, y):
global x_ball, y_ball
if x_ball <= scene.wnd_width/2 - 10*turtle.shapesize()[1]:
turtle.setposition(x_ball, y_ball)
x_ball += 10
screen.ontimer(play(0,0), 500)
else:
x_ball = 100 - scene.wnd_width/2; y_ball = 0
screen.mainloop()
scene = Template();
turtle = scene.controlButtons()
screen = scene.screen
prep()