【问题标题】:How to print time the button got clicked in the Tkinter window and display it in Tkinter window?如何打印在 Tkinter 窗口中单击按钮的时间并将其显示在 Tkinter 窗口中?
【发布时间】:2019-06-30 13:00:20
【问题描述】:

我有一个 Python 代码,它从 SQL 服务器运行查询,并在 Tkinter 中单击运行查询按钮时返回输出。 问题是有时查询需要大约 10-20 分钟才能完成,我不知道查询需要多少时间才能完成。

下面的代码是 Tkinter 在屏幕上打印的示例。

from tkinter import *    

def command(d):
    print(d)

a = Tk()
b = []

for c in range(0, 5):
    x = Button(a, text=c, command=lambda j=c: command(j)))
    x.pack()
    b.append(x)

a.mainloop()

所以我正在考虑添加一个状态栏来打印单击按钮的时间,并在显示消息框后再次记录该过程完成的时间。

【问题讨论】:

标签: python tkinter


【解决方案1】:

您可以使用 datetime 模块获取当前时间并为按钮分配回调以在显示屏上更改它(datetime.datetime.now() 获取当前时间,标签小部件与变量相关联,当变量改变,标签也改变):

import tkinter as tk
import datetime


def command():
    global time
    time.set(str(datetime.datetime.now()))


root = tk.Tk()
time = tk.StringVar()
time.set('0')
button = tk.Button(root, text='Print time', command=command)
button.pack()
label = tk.Label(root, textvariable=time)
label.pack()

root.mainloop()

【讨论】:

  • 部分问题是询问如何在窗口中显示它。这只会打印到标准输出。
  • 答案已更新,提出了一种在 tkinter 窗口中也显示时间的解决方案。
猜你喜欢
  • 2016-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 2022-01-22
  • 2014-03-25
  • 1970-01-01
相关资源
最近更新 更多