Skip to content Skip to sidebar Skip to footer

How To Output Variable On Turtle Screen?

I want to output a variable on the Turtle screen. But as the variable changes, the previous value is still on the screen. Thus, the values are overlapped. Method turtle.clear() doe

Solution 1:

There are a couple of things we can do to improve the situation. The first is to use the Undo feature of turtle to remove the old time information as a way of clearing it. Second, we can use tracer() and update() to control animation updates to get flicker under control:

from turtle import Turtle, Screen
from math import pi, sin, cos

screen = Screen()

body = Turtle(shape="circle")
body.color('red')
body.penup()

time_t = Turtle(visible=False)  # For time output
time_t.penup()
time_t.setposition(200, 200)  # In this position I want to output variable
time_t.write("t = " + str(0))

screen.tracer(0)  # Control animation updates ourselfdefMotion(A=100, omega=5, N=2):
    n = 0
    t = 0defx_pos(t):
        return A * cos(0.5 * omega * t)  # xdefy_pos(t):
        return A * sin(1 * omega * t)  # Ky

    body.setposition(x_pos(t), y_pos(t))
    body.pendown()

    while n < N:
        body.setposition(x_pos(t), y_pos(t))

        t = round(t + 0.01, 2)
        time_t.undo()  # undraw the last time update
        time_t.write("t = " + str(t))  # Show the time variable t on screen
        screen.update()

        ifint(round(t / (2 * pi / omega), 2)) == n + 1:
            n = n + 1

Motion()

screen.exitonclick()

BTW, very cool use of turtle! Let's go a step further: make the motion continuous; enable the exit on click at any point during the animation; don't make the body turtle visible until it's in its initial position; bump up the font size so we can see the time:

from turtle import Turtle, Screen
from math import pi, sin, cos

def motion():
    global n, t
    body.setposition(x_pos(t), y_pos(t))

    t = round(t + 0.01, 2)
    time_t.undo()  # undraw the last time update
    time_t.write("t = " + str(t), font=font)  # Show the time variable t on screen
    screen.update()

    if int(round(t / (2 * pi / omega), 2)) == n + 1:
        n = n + 1
        if (n >= N):
            n = t = 0

    screen.ontimer(motion, 10)

def x_pos(t):
    return A * cos(0.5 * omega * t)  # x

def y_pos(t):
    return A * sin(1 * omega * t)  # Ky

A = 100
omega = 5
N = 2
n = t = 0

font = ("Arial", 12, "normal")

screen = Screen()
screen.tracer(0)  # Control animation updates ourself

body = Turtle(shape="circle", visible=False)
body.color('red')
body.penup()
body.setposition(x_pos(t), y_pos(t))
body.pendown()
body.showturtle()

time_t = Turtle(visible=False)  # For time output
time_t.penup()
time_t.setposition(200, 200)  # In this position I want to output variable
time_t.write("t = " + str(0))

screen.ontimer(motion, 100)

screen.exitonclick()

Post a Comment for "How To Output Variable On Turtle Screen?"