2016-09-28 18 views
1

这是我写的(很多来自在线的灵感,因为我是一名学生,刚开始学习python)。当我打开该程序时,只需一个按钮即可完成GUI。当我按下按钮时,它会显示它应该的时间。但是,如果我关闭弹出窗口并再次按下,时间与上次相同。简而言之:我必须重新打开程序才能显示当前时间(因为它在打开后不会以当前时间更新)。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() 

回答

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里面每次更新按钮点击后

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() 
+0

@GI Jose这很好。 – Ch4r