This is the Recipe you are referencing:
# Shows a form that's a running counter
# this is the basic design pattern if you can keep your reading of the
# form within the 'with' block. If your read occurs far away in your code from the form creation
# then you will want to use the NonBlockingPeriodicUpdateForm example
def NonBlockingPeriodicUpdateForm_ContextManager():
with sg.FlexForm('Running Timer', auto_size_text=True) as form:
text_element = sg.Text('', size=(10, 2), font=('Helvetica', 20), text_color='red', justification='center')
layout = [[sg.Text('Non blocking GUI with updates', justification='center')],
[text_element],
[sg.T(' ' * 15), sg.Quit()]]
form.LayoutAndRead(layout, non_blocking=True)
for i in range(1,500):
text_element.Update('{:02d}:{:02d}.{:02d}'.format((i // 100) // 60, (i // 100) % 60, i % 100))
button, values = form.ReadNonBlocking()
if values is None or button == 'Quit': # if user closed the window using X
break
time.sleep(.01)
else:
# if the loop finished then need to close the form for the user
form.CloseNonBlockingForm()
Your question is about the last line of the code, right? The CloseNonBlockingForm call.
The reason for this is that the Quit button closes the form. If a different button-type has been used, like a ReadFormButton that does not close the form, then a Close form would be required in that instance too. If you would like I can post an example using a button that doesn't close the form.
Here's the same example, except using a different button type which will require the form to be closed.
def NonBlockingPeriodicUpdateForm_ContextManager():
with sg.FlexForm('Running Timer', auto_size_text=True) as form:
text_element = sg.Text('', size=(10, 2), font=('Helvetica', 20), text_color='red', justification='center')
layout = [[sg.Text('Non blocking GUI with updates', justification='center')],
[text_element],
[sg.T(' ' * 15), sg.ReadFormButton('Quit')]]
form.LayoutAndRead(layout, non_blocking=True)
for i in range(1,500):
text_element.Update('{:02d}:{:02d}.{:02d}'.format((i // 100) // 60, (i // 100) % 60, i % 100))
button, values = form.ReadNonBlocking()
if values is None or button == 'Quit': # if user closed the window using X
break
time.sleep(.01)
form.CloseNonBlockingForm()