Open In App
Related Articles

Asynchronisation Usage in PySimpleGUI

Improve Article
Save Article
Like Article

We use this design pattern for projects that actually will need to poll or output something on a regular basis. In this case, we’re indicating we want a timeout=10 in our
call. Also, this will cause the call to return a “timeout key” as the event every 10 milliseconds has passed without some GUI thing happening first. The timeout key is PySimpleGUI.TIMEOUT_KEY which is usually written as sg.TIMEOUT_KEY in normal PySimpleGUI code.

Please be cautious when you are using windows with a timeout. You will rarely need to use a timeout=0 . A zero value is a non-blocking call, so we need not try to abuse this design pattern.
A short note about timers is that this is not a good design for a stopwatch as it can easily drift. This would never pass for a nice solution in a bit of commercial code. For better accuracy, we should always get the actual time from a reputable source, maybe from the operating system. We can use that as what you use to measure and display the time.

To understand it, we will implement a Stopwatch in Python using PySimpleGUI.

import PySimpleGUI as sg
layout = [  [sg.Text('Stopwatch', size =(20, 2), justification ='center')],
            [sg.Text(size =(10, 2), font =('Arial', 20), justification ='center', key ='-OUTPUT-')],
            [sg.T(' ' * 5), sg.Button('Start / Stop', focus = True), sg.Quit()]]
window = sg.Window('Stopwatch Timer', layout)
timer_running, counter = True, 0
# Event Loop
while True:  
    # Please try and use as high of a timeout value as you can                               
    event, values = = 10
    # if user closed the window using X or clicked Quit button
    if event in (None, 'Quit'):             
    elif event == 'Start / Stop':
        timer_running = not timer_running
    if timer_running:
        window['-OUTPUT-'].update('{:02d}:{:02d}.{:02d}'.format((counter // 100) // 60
                                                 (counter // 100) % 60, counter % 100))
        counter += 1


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 27 Jul, 2020
Like Article
Save Article
Similar Reads
Complete Tutorials