Home python Timer on Python

Timer on Python

Author

Date

Category

I write a small utility on Python 2.7 + Tkinter. It was necessary to count the time between the presses on the button. Those. There is a button by clicking on which the timer must be activated (counting in seconds); When repeatedly pressing the countdown is stopped and the time is output. For example, so:

from tkinter import *
root = tk ()
Button1 = Button (root, width = 5, text = ".", Command = Timer)
Button1.pack ()
Def Timer ():
 # Here should be a timer
root.mainloop ()

Answer 1, Authority 100%

as happened everywhere – remember the time of the first press, to subtract it from the time of the second click …

time.time

currenttime = time.time ()

Answer 2, Authority 50%

This option does not block the script execution script. This means that you launched a timer and he is quietly waiting for the expansion of time, and the program works further.

import threading
DEF TIMER (Timeout):
  Timer = Threading.timer (Timeout, Func)
  Timer.Start ()
# Timeout - time in seconds
# FUNC - the function that is executed after the time

Answer 3, Authority 25%

Import Time
# here got the first click
Currenttime = time.time ()
While 1:
--- # You get all subsequent clicks
--- CurrentTime = Time.time () - CurrentTime
--- Print (CurrateTime)
Time.time () function returns time in milliseconds from some date there

Answer 4, Authority 25%

To show the time between successive presses on the button (TIMER () calls), you can use TIME.MONOTONIC () function, the value of which cannot go back and does not depend on the system time change:

#! / usr / bin / env python3
From Time Import Monotonic AS NOW
From Tkinter Import TK, Button
Def Timer (Times = [NOW ()]):
  Times.append (now ()) # Saving the current time by pressing the button
  Time_Diff = Times [-1] - Times.pop (0) # Time between the latest clicks
  Button ['text'] = '{: 4.0f} MS'.Format (1000 * Time_Diff) # Show
root = tk ()
Button = Button (root, text = "Click me", Command = Timer)
Button.pack ()
# CENTER WINDOW
root.eval ('TK :: PLACEWINDOW% S Center'% root.winfo_pathname (root.winfo_id ()))
root.mainloop ()

Use the variable values ​​for the default function parameters such as Times The list in the example is not recommended in the general case. Instead, create a class or closure, which will store the timer value from the past button pressing.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions