Skip to content
Related Articles

Related Articles

Improve Article

Asynchronisation Usage in PySimpleGUI

  • Last Updated : 27 Jul, 2020

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


 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :