淘先锋技术网

首页 1 2 3 4 5 6 7

Python是一种优秀的高级编程语言,可以实现各种功能,例如使用Python画时钟。下面的代码将解释如何使用Python绘制一个时钟。

import turtle
import time
wn = turtle.Screen()
wn.bgcolor("black")
wn.setup(width=600, height=600)
wn.title("Python Clock")
wn.tracer(0)
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.pensize(4)
def draw_clock(h, m, s, pen):
pen.up()
pen.goto(0, 200)
pen.setheading(180)
pen.color("green")
pen.pendown()
pen.circle(200)
pen.penup()
pen.goto(0,0)
pen.setheading(90)
for i in range(12):
pen.fd(170)
pen.pendown()
pen.fd(20)
pen.penup()
pen.goto(0,0)
pen.rt(30)
# Hour Hand
pen.penup()
pen.goto(0,0)
pen.color("white")
pen.setheading(90)
angle = (h / 12) * 360
angle += (m / 60) * 30
pen.rt(angle)
pen.pendown()
pen.fd(80)
# Minute Hand
pen.penup()
pen.goto(0,0)
pen.color("blue")
pen.setheading(90)
angle = (m / 60) * 360
angle += (s / 60) * 6
pen.rt(angle)
pen.pendown()
pen.fd(120)
# Second Hand
pen.penup()
pen.goto(0,0)
pen.color("red")
pen.setheading(90)
angle = (s / 60) * 360
pen.rt(angle)
pen.pendown()
pen.fd(160)
while True:
h = int(time.strftime("%I"))
m = int(time.strftime("%M"))
s = int(time.strftime("%S"))
draw_clock(h, m, s, pen)
wn.update()
time.sleep(1)
pen.clear()

代码中使用turtle模块绘制时钟,其中时、分、秒针分别用不同颜色的线条绘制,秒针的长度最长,分针长度次之,时针最短。时钟上的刻度通过循环绘制,循环12次,每次移动30度,绘制一根长度为20的线条,并回到原点。最后,代码通过time模块控制秒针的转动,并将时分秒传递给draw_clock函数绘制出时钟。