Web Analytics Made Easy - Statcounter
Skip to content

Persistent Window With Text Element Updates

This simple program keep a window open, taking input values until the user terminates the program using the "X" button.

This Recipe has a number of concepts. * Element name aliases - Txt and In are used in the layout * Bind return key so that rather than clicking "Calculate" button, the user presses return key * No exit/close button. The window is closed using the "X" * Dark Green 7 theme - there are some nice themes, try some out for yourself * try/except for cathing errors with the floating point * These should be used sparingly * Don't place a try/except around your whole event loop to try and fix your coding errors * Displaying results using a Text element - Note: be sure and set the size to a large enough value

math_game

import PySimpleGUI as sg

sg.theme('Dark Green 7')

layout = [ [sg.Txt('Enter values to calculate')],
           [sg.In(size=(8,1), key='-NUMERATOR-')],
           [sg.Txt('_'  * 10)],
           [sg.In(size=(8,1), key='-DENOMINATAOR-')],
           [sg.Txt(size=(8,1), key='-OUTPUT-')  ],
           [sg.Button('Calculate', bind_return_key=True)]]

window = sg.Window('Math', layout)

while True:
    event, values = window.read()

    if event != sg.WIN_CLOSED:
        try:
            numerator = float(values['-NUMERATOR-'])
            denominator = float(values['-DENOMINATAOR-'])
            calc = numerator/denominator
        except:
            calc = 'Invalid'

        window['-OUTPUT-'].update(calc)
    else:
        break