Skip to content Skip to sidebar Skip to footer

Threads And Time + Tkinter In Python

In tkinter I have made a password GUI some people have helped me with other things with it. The problem is: I have made a file called timeloadin it there is a while loop. When I im

Solution 1:

You shouldn't use long or infinite loops in tkinter, they will prevent the GUI from responding to user actions. A correct way to periodically update a field such as time is to use the tkinter .after method.

See the below example of a basic program where a label is updated with the current time every 1 second.

try:
    import tkinter as tk
except:
    import Tkinter as tk

import datetime

classApp(tk.Frame):
    def__init__(self,master=None,**kw):
        #Create the widgets
        tk.Frame.__init__(self,master=master,**kw)
        self.timeStr = tk.StringVar()
        self.lblTime = tk.Label(self,textvariable=self.timeStr)
        self.lblTime.grid()
        #Call the update function/method to update with current time.
        self.update()

    defupdate(self):
        self.timeStr.set(datetime.datetime.now())
        ## Now use the .after method to call this function again in 1sec.
        self.after(1000,self.update)


if __name__ == '__main__':
    root = tk.Tk()
    App(root).grid()
    root.mainloop()

Post a Comment for "Threads And Time + Tkinter In Python"