python - 如何在 Tkinter 窗口中获取/打印每秒更新时间

标签 python tkinter

我想使用 Tkinter 在窗口标签上打印当前时间(以秒为单位),但不是每 500 毫秒更新一次,而是保持不变。

我能做些什么来把这件事做好吗?

def timeout():
    t=time.time()
    window.after(500, timeout)
    return t

window = Tkinter.Tk()
window.title("Example")


time_label= Tkinter.Label(text=timeout(),
                    bg="black",fg="white").grid(row=1,column=2)        

window.geometry("100x100+100+100")
window.after(500, timeout)
window.mainloop()

我应该使用除标签之外的其他东西吗?

最佳答案

该标签将获取当前时间,然后不再执行任何操作。 timeout 函数将在半秒后调用 doing_it,但我没有在任何地方看到它的定义。您需要执行以下操作:

def timeout():
    time_label.config(text=time.time())
    window.after(500, timeout)

window = Tkinter.Tk()
window.title("Example")


time_label= Tkinter.Label(text='',
                    bg="black",fg="white")
time_label.grid(row=1,column=2)        

timeout()
window.geometry("100x100+100+100")
window.mainloop()

这会将label初始化为空字符串,然后立即调用timeout。该函数将标签配置为当前时间,然后对自身的调用进行排队。经过必要的时间后,Tkinter 将调用 timeout,它会更新 label 并排队对其自身的另一个调用。这将持续下去,直到您停止它为止。如果您想这样做,请创建一个标志(例如 running=True)并在调用 after() 之前检查它。然后,当您将其设置为 False 时,timeout() 将停止告诉 Tkinter 调用它。

关于python - 如何在 Tkinter 窗口中获取/打印每秒更新时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30853335/

相关文章:

python - 运行时警告: A class named 'Individual' has already been created and it will be overwritten

python - Toplevel.deiconify() 的替代方案

Python 参数在打印时返回 "<class ' tkinter.StringVar'>"

python - TypeError : expected httplib. 消息,得到 <type 'instance' >。在 GAE 上使用 requests.get(url) 时

python - 使用 pymongo 从/向磁盘加载和保存 mongoDB 数据库

Python 2.7 : Check if excel file is already open in program before saving it

python - Tkinter回调异常: matplotlib animation

python - tkinter-连接到文本小部件的滚动条可见,但没有任何 slider 。

python - 一键阻止打开多个窗口

python - 从 python 中执行命令行程序