Tkinter 时钟与 Windows 时钟不同步 [英] Tkinter clock not in sync with Windows clock

查看:32
本文介绍了Tkinter 时钟与 Windows 时钟不同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注这个教程用 tkinter 制作时钟,我遇到的问题是 lbl.after(1000, time) 行,它使函数等待一秒钟,然后重新运行时间函数.

I was following this tutorial on making a clock with tkinter and the problem I'm having is with the line lbl.after(1000, time) which makes the function wait one second and then rerun the time function.

如果您在 12:00:00.600 启动程序,程序会等待一秒钟,然后在 12:00:01 之后的 0.600 微秒处显示新时间,而不是恰好在 12:00:01.如果您让 Windows 时钟和程序并行运行,则 Windows 时钟总是会稍微快一些.我不确定他们是如何让它在他们的视频中工作的,我复制并粘贴了他们的代码,但仍然遇到同样的问题.

If you start your program at 12:00:00.600, the program waits one second and then displays the new time at .600 microseconds after 12:00:01 rather than at 12:00:01 exactly. If you have the windows clock and the program running side by side, the windows clock will always be slightly faster. I'm not sure how they got it to work in their video, I copied and pasted their code and still had the same issue.

我还看到了其他人使用 lbl.after(100, time) 的代码,它每 0.100 微秒而不是每秒重新运行该函数,它有点工作,但现在仍然有点然后.

I also saw someone else's code using lbl.after(100, time) which reruns the function every .100 microseconds rather than every second and it sort of works but it's still off a little every now and then.

在我使用 tkinter 添加 gui 的原始程序中,我使用以下函数来显示我的时间,它几乎与 Windows 时钟完全同步.

In my original program that I'm adding a gui to with tkinter, I used the following function to display my time and it would be almost perfectly in sync with the windows clock.

import datetime as dt


def wait_until_new_second():
    current_time = dt.datetime.now().time()
    previous_time = current_time

    while previous_time.second == current_time.second:
        current_time = dt.datetime.now().time()


def display_clock():
    while True:
        wait_until_new_second()
        print(dt.datetime.now().strftime('%H:%M:%S'))


display_clock()

是否可以在 tkinter 上运行与 Windows 时钟同步的时钟?

Is it possible to have a clock running on tkinter in sync with the windows clock?

和/或

有没有办法告诉 tkinter 使用我的 wait_until_new_second() 函数等待而不是等待 1 秒,比如 lbl.after(wait_until_new_second, time)?

Is there a way to tell tkinter to wait using my wait_until_new_second() function instead of waiting 1 second, something like lbl.after(wait_until_new_second, time)?

推荐答案

使用线程可以几乎(不完全)与系统时钟同步:

Using thread can be almost (not completely) in sync with system clock:

from datetime import datetime
import threading
import time
import tkinter as tk

root = tk.Tk()

clock = tk.StringVar()
tk.Label(root, textvariable=clock, font="Times 20 bold", fg='light green', bg="dark green").pack()

def tick():
    while True:
        now = datetime.now()
        clock.set(now.strftime("%T"))
        time.sleep(1-now.microsecond/1000000)

threading.Thread(target=tick, daemon=True).start()
root.mainloop()

这篇关于Tkinter 时钟与 Windows 时钟不同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆