Python-Art, Clock

# in the way of user defined shape
import turtle as t
import datetime as d
def skip(step):  # lift pen up and go to another position
    t.penup()
    t.forward(step)
    t.pendown()
def drawClock(radius):  # draw clock body
    t.speed(0)
    t.mode("logo")  # set mode to Logo
    t.hideturtle()
    t.pensize(7)
    t.home()  # back to center
    for j in range(60):
        skip(radius)
        if (j % 5 == 0):
            t.forward(20)
            skip(-radius - 20)
        else:
            t.dot(5)
            skip(-radius)
        t.right(6)
def makeHand(pointName, len):  # hands of clock: hour hand, minute hand and second hand
    t.penup()
    t.home()
    t.begin_poly()
    t.back(0.1 * len)
    t.forward(len * 1.1)
    t.end_poly()
    poly = t.get_poly()
    t.register_shape(pointName, poly)  # registered as a shape
def drawHand():  # draw hand
    global hourHand, minuteHand, secondHand, fontWriter
    makeHand("hourHand", 100)
    makeHand("minuteHand", 120)
    makeHand("secondHand", 140)
    hourHand = t.Pen()  # every hand is a new turtle
    hourHand.shape("hourHand")
    hourHand.shapesize(1, 1, 6)
    minuteHand = t.Pen()
    minuteHand.shape("minuteHand")
    minuteHand.shapesize(1, 1, 4)
    secondHand = t.Pen()
    secondHand.shape("secondHand")
    secondHand.pencolor('red')
    fontWriter = t.Pen()
    fontWriter.pencolor('gray')
    fontWriter.hideturtle()
def getWeekName(weekday):
    weekName = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    return weekName[weekday]
def getDate(year, month, day):
    return "%s-%s-%s" % (year, month, day)
def realTime():
    curr = d.datetime.now()
    curr_year = curr.year
    curr_month = curr.month
    curr_day = curr.day
    curr_hour = curr.hour
    curr_minute = curr.minute
    curr_second = curr.second
    curr_weekday = curr.weekday()
    t.tracer(False)
    secondHand.setheading(360 / 60 * curr_second)
    minuteHand.setheading(360 / 60 * curr_minute)
    hourHand.setheading(360 / 12 * curr_hour + 30 / 60 * curr_minute)
    fontWriter.clear()
    fontWriter.home()
    fontWriter.penup()
    fontWriter.forward(80)
    # write with turtle
    fontWriter.write(getWeekName(curr_weekday), align="center", font=("Courier", 14, "bold"))
    fontWriter.forward(-160)
    fontWriter.write(getDate(curr_year, curr_month, curr_day), align="center", font=("Courier", 14, "bold"))
    t.tracer(True)
    print(curr_second)
    t.ontimer(realTime, 100)  # call realTime() every 100 milli second
def main():
    t.tracer(False)
    drawClock(160)
    drawHand()
    realTime()
    t.tracer(True)
    t.mainloop()
if __name__ == '__main__':
    main()

dahan1999

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts