-1

I am trying to build something in Tkinter, in which I want to add a clock to tell the user how much time is left. How can I implement this?

I have tried to find it, but they give me after() function. How can I be sure that it will be called after exactly one second?

jerrymouse
  • 16,964
  • 16
  • 76
  • 97
Palvit Garg
  • 137
  • 2
  • 9
  • Tkinter's timing is good enough that the user won't notice a difference. If you're keeping precise track of time for extremely long periods, you can sync the countdown to the system time occasionally. Can you provide more detail about what/how much/etc. you're counting? – TigerhawkT3 Dec 14 '15 at 08:55
  • By the way I flagged this as duplicate because the answer has timer's code and also explanation for why you can't be sure. `Bear in mind that after doesn't guarantee the function will run exactly on time. It only schedules the job to be run after a given amount of time. It the app is busy there may be a delay before it is called since Tkinter is single-threaded. The delay is typically measured in microseconds.` – Lafexlos Dec 14 '15 at 09:40
  • 1
    I like how the OP mentions that he's seen `after()` but isn't sure of the accuracy, and then the answers are just examples of how to use `after()` with no information about its accuracy. – TigerhawkT3 Dec 14 '15 at 10:10

1 Answers1

1

You can use time to get time left and a label to show it.

'%.1f' % (newtime - TIME) is used to have always one digit after ..
This is a simple example:

from Tkinter import*
import time

the_time=''


TIME = newtime = time.time()

class Window(Frame):
    def __init__(self,master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()


    def create_widgets(self):
        #Create a label that displays time:
        self.display_time=Label(self, text=the_time)
        self.display_time.grid(row=0, column=1)

        def change_value_the_time():
            global the_time
            newtime = time.time()
            if newtime != the_time:
                the_time= '%.1f' % (newtime - TIME)
                self.display_time.config(text=the_time, font="40")
            self.display_time.after(20, change_value_the_time)

        change_value_the_time()

root=Tk()
root.title("Test")
root.geometry("200x200")
app=Window(root)
root.mainloop()
Kenly
  • 24,317
  • 7
  • 44
  • 60