Python Forum

Full Version: Change Label Every 5 Seconds
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have written a loop that changes a Label. However, I don't know how to wait until the changed label is displayed to start my time delay. If I change the Label then immediately time.sleep(5), the label never gets changed. If I remove the sleep and go though the loop once, the label does get changed but obviously only 1 time. How can I accomplish this? TIA.
Thanks for that link. I now see what to do but not how to do it. I am struggling trying to figure out what to use for 'after'. The window in question is saved as self.root. If I understand my code should simply be:
print('starting scan')
sensors=self.xml.getSensors()
scan=True
while (scan):
     junk,sensID=self.menu.getNextMenu()
     sens=functions.findID(sensors,sensID)
     print(sensID,sens.temp)
     self.updateLines(sensID,'  *tmp: '+ str(sens.temp))
     self.root.after(0)
     time.sleep(5)
Unfortunately that doesn't work so it is not as simple has I had hoped. The 'updateLines' method is:
def updateLines(self,first,second):
        self.drawLine1(first)
        self.drawLine2(second)

def drawLine1(self,str):
        self.line1=CL.CustomFont_Label(self.root,text=self.pad(str),font_path=se
lf.fontPath,size=36).grid(row=0,column=0,columnspan=5)

def drawLine2(self,str):
        self.line2=CL.CustomFont_Label(self.root,text=self.pad(str),font_path=se
lf.fontPath,size=36).grid(row=1,column=0,columnspan=5)
CustomFont_Label is from this recipe.
It will be something more like this
    def scanning(self):
        junk,sensID=self.menu.getNextMenu()
        sens=functions.findID(self.sensors,sensID)
        print(sensID,sens.temp)
        self.updateLines(sensID,f'  *tmp: {sens.temp}')
        if self.scan:
            self.root.after(5000, self.scanning)
after uses a separate thread to call the passed in callable once the duration of milliseconds is up, the GUI will continue to function as normal.

Example
import tkinter as tk
import datetime


class MainFrame(tk.Frame):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.label = tk.Label(self)
        self.label.pack()
        self.pack()
        self.every5sec()

    def every5sec(self):
        self.label['text'] = datetime.datetime.now()
        self.after(5000, self.every5sec)


if __name__ == '__main__':
    app = tk.Tk()
    main_frame = MainFrame()
    app.mainloop()
Thanks. I think I see said the blind man as he picked up a hammer and saw.