且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

之后的 Tkinter 在时钟倒带中幸存下来

更新时间:2023-02-26 17:38:10

不幸的是,Tkinter 和 Tcl 解释器都没有直接解决您的问题的方法.after(ms, func) 方法基于同名 Tcl 命令,它根据当前系统时间加上作为参数传递的毫秒数创建一个内部计时器.

Unfortunately, neither Tkinter nor Tcl interpreter have an straightforward solution to your problem. The after(ms, func) method is based on the Tcl command of the same name, which creates an internal timer based on the current system time plus the amount of milliseconds passed as parameter.

如果你好奇,你可以直接从 Tcl/Tk 源代码:

In case you are curious, you can check it out directly from the Tcl/Tk source code:

Tcl_GetTime(&wakeup);
wakeup.sec += (long)(ms / 1000);
wakeup.usec += ((long)(ms % 1000)) * 1000;
if (wakeup.usec > 1000000) {
    wakeup.sec++;
    wakeup.usec -= 1000000;
}
afterPtr->token = TclCreateAbsoluteTimerHandler(&wakeup,
    AfterProc, afterPtr);

鉴于此限制,我会采用纯 Python 方法,例如使用 计时器:

Given this limitation, I would go for a pure Python approach, like using a Timer:

import time
import threading
import tkinter as tk

root = tk.Tk()

def say_hi():
    print(time.perf_counter(), "-", "Hi after 30sec!")
    root.destroy()

print(time.perf_counter(), "-", "Waiting 30sec")
threading.Timer(30, say_hi).start()
root.mainloop()

它还具有运行在单独线程上的优点,不仅可以防止在计时器间隔期间阻塞 GUI,而且还可以防止在执行回调函数时阻塞.

It also has the advantage that runs on a separate thread, preventing not only blocking the GUI during the timer interval but also while executing the callback function.