Python tkinter .pack/.pack_forget memory issue
Question: I've been teaching myself Python for a few months now and have proceed into
learning some GUI techniques.

I wrote this simple script based off a pack_remove example I found within a
book. My script simply displays local and UTC time every second. Granted the
only difference is the hour, I would still like to redisplay every second.

The script works, yet my RAM is consistently increasing with every time
display. I start out with around 4mb then after 2 hours or so the script uses
25mb. This makes some sense to me, but I was curious if there was a way
display new times every second, but reduce the memory usage of such a simple
clock display.

Or am I using an inefficient technique to re-display data in a GUI at a high
frequency?

Here is my code:

    
    
    from tkinter import *
    import time
    
    class TimeDisplay(Frame):
        def __init__(self,msecs = 1000):
            Frame.__init__(self)
            self.msecs = msecs
            self.pack()
            utc_time = Label(self, text='')
            utc_time.pack()
            cst_time = Label(self, text='')
            cst_time.pack()
            self.utc_time = utc_time
            self.cst_time = cst_time
            self.repeater()
    
        def repeater(self):
            self.utc_time.pack_forget()
            self.cst_time.pack_forget()
            self.utc_time = Label(self, text= 'UTC: ' + time.strftime('%Y/%m/%d %H:%M:%S',time.gmtime()))
            self.utc_time.pack()
            self.utc_time.config(bg='navy',fg='white')
            self.cst_time = Label(self, text= 'CST: ' + time.strftime('%Y/%m/%d %H:%M:%S',time.localtime()))
            self.cst_time.pack()
            self.cst_time.config(bg='navy',fg='white')
            self.after(self.msecs, self.repeater)        
    
    
    if __name__ == '__main__': TimeDisplay(msecs=1000).mainloop()    
    

Thanks in advance


Answer: `pack_forget` doesn't destroy anything, it just makes it non-visible. This is
a GUI version of a memory leak -- you keep creating objects without ever
destroying them.

So, the first lesson to learn is that you should destroy a widget when you are
done with it.

The more important lesson to learn is that you don't have to keep destroying
and recreating the same widget over and over. You can change the text that is
displayed with the `configure` method. For example:

    
    
    self.utc_time.configure(text="...")
    

This will make your program not use any extra memory, and even use
(imperceptibly) less CPU.

