Python tkinter .pack/.pack_forget memory issue - python

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

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.

To actually free widget's memory you should also call it's .destroy() method. This prevents memory leaking in your case.
However a more efficient way to implement the stuff is to associate string variable with Label widget like this:
v = StringVar()
Label(master, textvariable=v).pack()
v.set("New Text!")
see http://effbot.org/tkinterbook/label.htm for reference

Related

Can You Call '.after' Twice in a Function?

I am asking a question in good faith here. I've had a lot of trouble on StackOverflow; I know this is probably Googleable, but I lack the prerequisite knowledge to do so. Please keep that in mind and be kind.
The Overall Goal
I am creating a digital clock which functions normally for five minutes, and then accelerates rapidly for two minutes. Then, it will freeze for a certain amount of time, show the correct time, and the program repeats.
Immediate Goal
I need to call my faketime function from within my time function. When I add the second .after, I get an IndentationError: unindent does not match any outer indentation level. As my indentation appears to fine, I think the issue is elsewhere. Can use you use .after twice in a function? If not, how can I accomplish this? Thank you!
Code
from tkinter import *
from tkinter.ttk import *
# importing strftime function to
# retrieve system's time
from time import strftime
# creating tkinter window
root = Tk()
root.title('Clock')
# This function is used to
# display time on the label
def newtime():
faketime = "Test"
lbl.config(text=faketime)
lbl.after(1000, time)
def time():
string = strftime('%H:%M:%S')
lbl.config(text=string)
lbl.after(1000, time)
lbl.after(300000, newtime())
# Styling the label widget so that clock
# will look more attractive
lbl = Label(root, font=('calibri', 40, 'bold'),
background='black',
foreground='red')
# Placing clock at the centre
# of the tkinter window
lbl.pack(anchor='center')
time()
mainloop()
Line 18 should be lbl.after(1000, newtime) instead of lbl.after(1000, time)
Comment out line 25 #lbl.after(300000, newtime())
HAPPY NEW YEARS!
Output image:

Python tkinter, labels, and function order

This seems so simple but I can't figure out what I need to do to remedy. I have a tkinter project and on a button press, a function runs that takes several seconds. I want a "loading..." type message while the function is running so it's obvious it's actually working and not crashed. I figured a label would be easy enough and on the first line of the function, have label1.set('loading') but I suppose because of the way functions work, the label doesn't set until the function is done running--which is not helpful.
I made a second short function
def update_status(message):
label1.set(message)
and for the button in tkinter, used command=lambda:[update_status('loading'),search()] in hopes that the update_status() function would run first, alter the label, and then the second search() function that takes upwards of 30 seconds would run. But I get the same effect.
What's the simplest way finish running the update_status() function--thereby updating my label acting as the "status", and THEN run the time consuming search() function?
I'm not opposed to something more complicated like a loading window or something similar, but just wanted something simple (I have not even googled any type of loading window--I'm mostly hung up on how to get 2 functions to run on a button click in a sequential order).
Hey I do not think you need 2 functions to do what you want. You simply have to update your root so that the label is directly updated.
Here is an example:
import tkinter as tk
import time
def update_status(message1, message2):
var.set(message1)
root.update()
time.sleep(5)
var.set(message2)
if __name__ == '__main__':
root = tk.Tk()
root.title("Wait for function")
var = tk.StringVar()
var.set('Waiting for input')
label1 = tk.Label(root, textvariable=var)
label1.pack()
Button1 = tk.Button(root, text="Wait", command=lambda:update_status('loading', 'done'))
Button1.pack()
root.mainloop()

How do you make a constantly refreshing canvas in Python?

I am currently trying to code a basic smartmirror for my coding II class in high school with Python. One thing I'm trying to do is create a welcome text that updates based on what button you press. I am reading the string for the canvas' text from a .txt document that changes depending what user I select. Is there any way to get this to automatically refresh when I change the document's text?
The code I am using to display the message is:
text2 = Canvas(tk, width=500, height=100)
welcometext = text2.create_text(200, 50, text=string, font=('Helvetica', 20, 'italic'))
text2.pack(side=TOP, anchor=Center)
The basic way to do this is have a loop. And every cycle of the loop you should check for user input and redraw. Make sure you break everything up into functions so your loop is clean. Something like this -
canvas = Canvas(tk, width=500, height=500)
text = ''
while(True) {
getUserInput(text)
draw(canvas, text)
}
You can use python's built in input function to get the user input in your getUserInput function.
As an aside, this is a naive approach, because the loop will wait for user input every time before redrawing. The proper way to do this would be to use threading. You could have a thread to capture user input while your main loop does other things. This can get complicated really fast though, due to data synchronization issues. I'd just stick with the naive approach for now.
Also, the variable text2 is misleading. Always try to name your variables to be exactly what they are. In this case, it's a Canvas object, so call it canvas.

Digital clock display - multithreading required?

Situation
I have the following Tkinter window:
And in the blank space on the right:
I want to be able to continuously update the time, like on a digital clock.
I will take the present time using:
time.strftime('%H:%<:%S')
I think this involves MultiThreading. But please tell me if there is some other way to do this.
The two white areas are input areas for the user.
Please note that the text will be entered in these fields. I don't want that to be affected.
What I think is that the function that will make the time to change after each second, will run on a different thread than the one that includes the text boxes.
The value of time will be in a Label:
a = Label(root,text=time.strftime('%H:%M:%S'))
a.grid(row=3,column=1)
Please give me the code for this function and also for the multithreading.
Please help me with this issue.
You don't need multithreading.
...
a = Label(root, text=time.strftime('%H:%M:%S'))
def update_time():
a['text'] = time.strftime('%H:%M:%S')
root.after(1000, update_time)
root.after(1000, update_time)
a.grid(row=3, column=1)
...

How to run a function in the background of tkinter [duplicate]

This question already has an answer here:
Tkinter locks Python when an icon is loaded and tk.mainloop is in a thread
(1 answer)
Closed 7 months ago.
I am new to GUI programming and I want to write a Python program with tkinter. All I want it to do is run a simple function in the background that can be influenced through the GUI.
The function counts from 0 to infinity until a button is pressed. At least that is what I want it to do. But I have no idea how I can run this function in the background, because the mainloop() of tkinter has control all the time. And if I start the function in an endless loop, the mainloop() cannot be executed and the GUI is dead.
I would like to return control back to the mainloop() after each cycle, but how can I get the control back from the mainloop() to the runapp-function without a user-triggered event?
Here is some sample code that kills the GUI:
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="START", command=self.runapp)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="RESTART", command=self.restart)
self.hi_there.pack(side=LEFT)
self.runapp()
def restart(self):
print "Now we are restarting..."
def runapp(self):
counter = 0
while (1):
counter =+ 1
time.sleep(0.1)
Event based programming is conceptually simple. Just imagine that at the end of your program file is a simple infinite loop:
while <we have not been told to exit>:
<pull an event off of the queue>
<process the event>
So, all you need to do to run some small task continually is break it down into bite-sized pieces and place those pieces on the event queue. Each time through the loop the next iteration of your calculation will be performed automatically.
You can place objects on the event queue with the after method. So, create a method that increments the number, then reschedules itself to run a few milliseconds later. It would look something like:
def add_one(self):
self.counter += 1
self.after(1000, self.add_one)
The above will update the counter once a second. When your program initializes you call it once, and from then after it causes itself to be called again and again, etc.
This method only works if you can break your large problem (in your case "count forever") into small steps ("add one"). If you are doing something like a slow database query or huge computation this technique won't necessarily work.
You will find the answer in this other question Tkinter locks python when Icon loaded and tk.mainloop in a thread.
In a nutshell, you need to have two threads, one for tkinter and one for the background task.
Try to understand this example : clock updating in backgroud, and updating GUI ( no need for 2 threads ).
# use Tkinter to show a digital clock
# tested with Python24 vegaseat 10sep2006
from Tkinter import *
import time
root = Tk()
time1 = ''
clock = Label(root, font=('times', 20, 'bold'), bg='green')
clock.pack(fill=BOTH, expand=1)
def tick():
global time1
# get the current local time from the PC
time2 = time.strftime('%H:%M:%S')
# if time string has changed, update it
if time2 != time1:
time1 = time2
clock.config(text=time2)
# calls itself every 200 milliseconds
# to update the time display as needed
# could use >200 ms, but display gets jerky
clock.after(200, tick)
tick()
root.mainloop( )
credits: link to site
I don't have sufficient reputation to comment on Bryan Oakley's answer (which I found to be very effective in my program), so I'll add my experience here. I've found that depending on how long your background function takes to run, and how precise you want the time interval to be, it can be better to put self.after call at the beginning of the recurring function. In Bryan's example, that would look like
def add_one(self):
self.after(1000, self.add_one)
self.counter += 1
Doing it this way ensures that the interval of time is respected exactly, negating any interval drift that might occur if your function takes a long time.
If you don't want to be away from those threads, I would like to give one suggestion for your GUI-
Place the function for your GUI just before the root.mainloop() statement.
Example-
root = tk.Tk()
.
.
graphicsfunction() #function for triggering the graphics or any other background
#function
root.mainloop()
Please up vote if you like.

Categories

Resources