首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tkinter动画-模拟模拟时钟

Tkinter动画-模拟模拟时钟
EN

Stack Overflow用户
提问于 2020-10-08 02:34:43
回答 1查看 148关注 0票数 0

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

代码语言:javascript
复制
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。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-08 17:42:31

这是我几年前写的一个时钟的代码片段。

代码语言:javascript
复制
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方法中,请注意,为了计算出时针的角度,我同时使用了小时h和分钟m的值。与分钟指针类似,我使用分钟和秒值来设置角度。

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

首先,你需要画一只手(实际上画在哪里并不重要)

代码语言:javascript
复制
hour_hand_line = canvas.create_line(250,250,350,250, fill="purple")

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

代码语言:javascript
复制
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的结束位置基于线的长度,并基于三角进行一些调整。然后,我们只需将线移动到该位置。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64250300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档