程序启动后,Python GUI不会更新信息

时间:2016-09-28 11:54:05

标签: python python-3.x user-interface tkinter

这就是我所写的(很多来自网上的灵感,因为我是一名学生,刚开始学习python)。当我打开程序时,只需一个按钮就可以看到GUI。当我按下按钮时,它会显示应该的时间。但是,如果我关闭弹出窗口,然后再次按下它,时间与上次相同。简而言之:我必须重新打开程序才能显示当前时间(因为它在打开后不会随当前时间更新)。

import Tkinter as tk
import tkMessageBox
import datetime



ctime = datetime.datetime.now() .strftime("%Y-%m-%d %H:%M:%S")
top = tk.Tk()
def showInfo():
    tkMessageBox.showinfo( "Today:", str(ctime))

B = tk.Button(top, text ="Click to show current time", command = showInfo)
B.pack()
top.mainloop()

2 个答案:

答案 0 :(得分:3)

试试这个:

import Tkinter as tk
import tkMessageBox
import datetime



top = tk.Tk()
def showInfo():
    ctime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    tkMessageBox.showinfo( "Today:", str(ctime))

B = tk.Button(top, text ="Click to show current time", command = showInfo)
B.pack()
top.mainloop()

ctime放在函数showInfo内,每次点击按钮时都会更新

答案 1 :(得分:2)

每次单击按钮时,您都可以使用方法获取当前时间:

import Tkinter as tk
import tkMessageBox
import datetime


def getTime():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

top = tk.Tk()
def showInfo():
    tkMessageBox.showinfo( "Today:", getTime())

B = tk.Button(top, text ="Click to show current time", command = showInfo)
B.pack()
top.mainloop()
相关问题