I am writing a small utility in Python 2.7 + Tkinter. It took time to count between button presses. Those. there is a button, by pressing which the timer should be activated (countdown in seconds); pressing it again will stop the time and display the time. For example:

from Tkinter import * root=Tk() button1 = Button(root, width=5, text=".", command=timer) button1.pack() def timer(): # Π—Π΄Π΅ΡΡŒ Π΄ΠΎΠ»ΠΆΠ΅Π½ Π±Ρ‹Ρ‚ΡŒ Ρ‚Π°ΠΉΠΌΠ΅Ρ€ root.mainloop() 

    3 answers 3

    Like everywhere else, remember the time of the first pressing, subtract it from the time of the second pressing ...

    time.time

     currentTime = time.time() 
    • It is possible in more detail - how to make it in Python? I have never dealt with the time module before. - Barlog_h
    • updated the answer - qnub
    • What will this feature look like? Another click should not be two, but an arbitrary number (the difference is displayed each time). Similar things are used, for example, in tests for the speed of clicks (calculate the difference between 2 and 1 click, 3 and 2, etc., and output the sum of the differences). PS Sorry for the stupid questions, I'm new. - Barlog_h
    • one
      @Barlog_h It is better to use time.monotonic() instead of time.time() (if available) to find the relative time difference. time.monotonic() works even during a leap second such as 2017-01-01 02:59:60 MSK - jfs
     import time #Ρ‚ΡƒΡ‚ ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠ»ΠΈ ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ ΠΊΠ»ΠΈΠΊ CurrentTime = time.time() while 1: ---#Ρ‚ΡƒΡ‚ ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ всС ΠΏΠΎΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠ΅ ΠΊΠ»ΠΈΠΊΠΈ ---CurrentTime = time.time()-CurrentTime ---print(CurrentTime) функция time.time() Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ врСмя Π² миллисСкундах начиная с ΠΊΠ°ΠΊΠΎΠΉ-Ρ‚ΠΎ Ρ‚Π°ΠΌ Π΄Π°Ρ‚Ρ‹ 

    To show the time between successive button presses ( timer() calls), you can use the time.monotonic() function , the value of which cannot go backwards and does not depend on a change in the system time:

     #!/usr/bin/env python3 from time import monotonic as now from tkinter import Tk, Button def timer(times=[now()]): times.append(now()) # сохраняСм Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π΅ врСмя ΠΏΠΎ Π½Π°ΠΆΠ°Ρ‚ΠΈΡŽ ΠΊΠ½ΠΎΠΏΠΊΠΈ time_diff = times[-1] - times.pop(0) # врСмя ΠΌΠ΅ΠΆΠ΄Ρƒ послСдними наТатиями button['text'] = '{:4.0f} мс'.format(1000 * time_diff) # ΠΏΠΎΠΊΠ°Π·Ρ‹Π²Π°Π΅ΠΌ root = Tk() button = Button(root, text="Π½Π°ΠΆΠΌΠΈ мСня", command=timer) button.pack() # center window root.eval('tk::PlaceWindow %s center' % root.winfo_pathname(root.winfo_id())) root.mainloop() 

    Using variable values ​​for default function parameters such as the times list in the example is not recommended in the general case. Instead, create a class or closure that will store the timer value from the last button click.