G.I Jose G.I Jose - 2 months ago 11
Python Question

Python GUI not updating info after program has launched

This is what I've written (alot of inspiration from online, since im a student and just started learning python). When I open the program, theres a GUI with one button. When I press the button it displays the time as it should. But if i close the popup window, and press it again, the time is the same as it was last time. In short: I have to re-open the program to display current time (since it does not update with current time after it opens).

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

Answer

Try this:

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

put ctime inside the function showInfo to update each time when clicked on the button