Skip to content

The Timer Class

The Timer is a utility class for accurately keeping track of elapsed time. It acts like a stopwatch and can be paused, stopped and restarted as required.

While there are app.set_interval() and app.set_timeout() methods for scheduling functions to run after a certain amount of time, the Timer class is more suitable for applications that require precise timekeeping, such as stopwatches, countdowns, or any situation where you need to track how much time has passed.

This example creates a simple stopwatch with Start, Stop, and Reset buttons. The Timer class is used to keep track of the elapsed time, and the set_interval() method is used to update the display every 100 milliseconds.

stopwatch.py
import gooeypie as gp
def update_time():
"""Updates the time display to MM:SS.mmm format"""
mins = stopwatch.minutes
secs = stopwatch.seconds
ms = stopwatch.milliseconds
formatted_time_lbl.text = f'{mins:02}:{secs:02}.{ms:03}'
def start_pause(event):
"""Starts or pauses the stopwatch depending on the current state."""
if start_pause_btn.text == 'Start':
stopwatch.start()
start_pause_btn.text = 'Pause'
else:
stopwatch.pause()
start_pause_btn.text = 'Start'
def stop(event):
"""Stops the stopwatch and resets the time to 00:00.000."""
stopwatch.stop()
start_pause_btn.text = 'Start'
app = gp.GooeyPieApp('Stopwatch')
stopwatch = gp.Timer()
# Create widgets
formatted_time_lbl = gp.Label('00:00.000')
formatted_time_lbl.style.font_size = 40
start_pause_btn = gp.Button('Start', start_pause)
stop_btn = gp.Button('Reset', stop)
# Add widgets to window
app.add(formatted_time_lbl, 1, 1, column_span=2, align_horizontal='center')
app.add(start_pause_btn, 1, 2, expand_horizontal=True)
app.add(stop_btn, 2, 2, expand_horizontal=True)
# Update the time display every 1ms (approx)
app.set_interval(1, update_time)
app.run()

You create a Timer with gp.Timer():

my_timer = gp.Timer()

This creates a new Timer, initialised to 0, which will not start until the start() method is callled.

NameTypeDescription
.timefloatGets the total seconds elapsed since the timer started.
.millisecondsintegerGets the milliseconds component of the elapsed time, as an integer from 0 to 999.
.secondsintegerGets the seconds component of the elapsed time, as an integer from 0 to 59.
.minutesintegerGets the minutes component of the elapsed time, as an integer from 0 to 59.
.hoursintegerGets the hours component of the elapsed time, as an integer.
.stoppedbooleanReturns a Boolean representing whether the timer is currently stopped.
.pausedbooleanReturns a Boolean representing whether the timer is currently paused.
NameDescription
start()Starts the timer, or continues the timer if it is paused. Has no effect if the timer is already running.
stop()Stops the timer and resets the time elapsed to 0.
pause()Pauses the timer. Timing can be resumed by calling start(). Has no effect if the timer is not running.
restart()Clears the timer and starts timing again.