【问题标题】:Tkinter animation - simulate an analogue clockTkinter 动画 - 模拟模拟时钟
【发布时间】:2020-10-07 18:34:42
【问题描述】:

我目前使用 Tkinter 构建了时钟和时针、分针和秒针。

hour_num = [3, 2, 1, 12, 11, 10, 9, 8, 7, 6, 5, 4]

for i in hour_num:
    text_x = ORIGIN[0] + clock_radius * math.cos(theta)
    text_y = ORIGIN[1] - clock_radius * math.sin(theta)
    theta += d_theta
    screen.create_text(text_x, text_y, text=i, font="Arial 25", fill="white")

## Time info
hour = datetime.now().hour
minute = datetime.now().minute
second = datetime.now().second

secondhand = screen.create_line(ORIGIN[0], ORIGIN[1], ORIGIN[0], ORIGIN[1] - clock_radius + 50, width=13, fill="blue")
minutehand = screen.create_line(ORIGIN[0], ORIGIN[1], ORIGIN[0], ORIGIN[1] - clock_radius + 70, width=13, fill="green")
hourhand = screen.create_line(ORIGIN[0], ORIGIN[1], ORIGIN[0], ORIGIN[1] - clock_radius + 90, width=13, fill="red")

所以现在画布看起来像这样: Screenshot

有人可以帮我用当前时间制作时钟指针吗?

我尝试使用三角函数来找出每小时之间的距离(取角与原点的余弦比)。首先,我意识到它不是完美的直角三角形,其次。时针将不现实:2:50 的时针将更接近 3 而不是 2。

谢谢

【问题讨论】:

  • 您可以同时使用小时和分钟来计算时针的角度。

标签: python-3.x tkinter


【解决方案1】:

这是我几年前写的时钟的 sn-p 代码。

def getHMS():
    time = datetime.now()
    h,m,s = time.hour, time.minute, time.second
    return h,m,s

def updateClock():
    h,m,s = getHMS()
    ac = -90    # Correction angle since 0degrees should be at the top
    ha = (((h%12)+(m/60))/12)*360 + ac
    ma = ((m + (s/60)) / 60 )*360 + ac
    sa = ((s / 60) * 360) + ac
    moveHand(hour_hand, ha)
    moveHand(minute_hand, ma)
    moveHand(second_hand, sa)
    canvas.after(1000,updateClock)

在 updateClock 方法中,请注意,为了计算时针 ha 的角度,我同时使用了小时 h 和分钟 m 值。与分针类似,我同时使用分钟和秒值来设置角度。

编辑:画手的一些额外帮助

首先你需要画一只手(不管它真的画在哪里)

hour_hand_line = canvas.create_line(250,250,350,250, fill="purple")

然后你需要根据当前时间使用我们计算的角度移动那只手

def moveHourHand(angle):
    hour_length = 150
    #Centre position of hand
    x1 = 250 
    y1 = 250
    #End Postition of hand
    x2 = x1 + hour_length * math.cos(math.radians(angle))
    y2 = y1 + hour_length * math.sin(math.radians(angle))
    #Move existing line to new position
    canvas.coords(hour_hand_line, x1,y1,x2,y2)

起始位置x1y1 是时钟的中心,线的结束位置x2y2 是基于线的长度并根据三角函数进行一些调整。然后我们只需将线移动到该位置即可。

【讨论】:

  • 你能给我更多关于 moveHand() 函数的提示吗?如何调整坐标使其与角度匹配?
  • @ENG2D 提供了一些额外的帮助。您需要做一些工作才能将所有内容整合在一起,但复杂的部分可供您使用。
  • 非常感谢,我没想到会有完整的答案,提示会很有帮助!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2018-09-19
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-11
相关资源
最近更新 更多