Is there any way to make Turtle make a line, undo it, and add another line on a loop?

Viewed 21

Yes, the title sounds stupid, but hear me out:

I'm trying to make a clock program, and I need the minutes and hours hands to actually 'move' by themselves (as in moving when the minute or hour changes, respectively) by undoing a line and drawing it again, but in a different place. However, instead of that, the hands of the clock go to the right positions right at the start of the program; for example, if you started the program at 2:49, it would put the hands at 2:49. Then, when you reach 2:50 (or any other time, for that matter), the hands stay in the same place, not updating with the time. The weird thing? There are no error messages or anything (this is the reason I made an account on stack overflow)

Here's the relevant parts of the code that I'm using:

import turtle
import datetime

tm_year,tm_mon,tm_mday,tm_hour,tm_min,tm_sec = map(int,time.localtime()[:6])

# I add extra values here to offset it for the next chunk of code
hora = tm_hour+360
minuto = tm_min+360
segundo = tm_sec+360

# I ran out of names for variables in the code so I resorted to español
while True:
    if hora != tm_hour:
        hour.undo()
        hour.seth(90)
        hour.rt(30*tm_hour)
        hour.fd(20)
        hora = tm_hour
    if minuto != tm_min:
        minute.undo()
        minute.seth(90)
        minute.rt(6*tm_min)
        minute.fd(60)
        minuto = tm_min
    if segundo != tm_sec:
        second.undo()
        second.seth(90)
        second.rt(6*tm_sec)
        second.fd(40)
        segundo = tm_sec
1 Answers

The turtle graphics suit is essentially a tkinter gui with tools for drawing 2dimensional graphics. As with most GUI's it is necessary to "give up" control of the program at some point and allow the GUI's mainloop to draw updates to screen and allow for any user interaction. As such any procedure that continues for long periods of time will lead to the window becoming frozen and unusable.

This is where events, and event listeners come in handy. In order for your clock to work using turtle graphics in a way that allows the window to continuously update itself on a second by second basis, you will need to use event listeners such as the ontimer listener.

Ill give you an example of how the second hand would operate using this method and leave the rest to you.

import turtle
import time

second = turtle.Turtle()

def second_timer():
    turtle.ontimer(second_hand_update, t=1000)

def second_hand_update():
    tm_sec = time.localtime().tm_sec
    second.undo()
    second.seth(90)
    second.rt(6*tm_sec)
    second.fd(100)
    second_timer()
    # second.screen.update()  # uncomment line to turn off the animation

# second.screen.tracer(0)   # uncomment line to turn off the drawing animation
second_hand_update()
turtle.mainloop()
Related