Skip to main content
 首页 » 编程设计

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

2025年05月04日62softidea

这是我写的(很多灵感来自网上,因为我是一名学生,刚开始学习 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() 

请您参考如下方法:

试试这个:

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 中,以便在每次单击按钮时更新