Asynchronisation Usage in PySimpleGUI

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 window.read
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.

filter_none

edit
close

play_arrow

link
brightness_4
code

import PySimpleGUI as sg
  
sg.theme('SandyBeach')
  
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 = window.read(timeout = 10
  
    # if user closed the window using X or clicked Quit button
    if event in (None, 'Quit'):             
        break
    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
window.close()

chevron_right


Output




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.