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.