How to integrate code with window in PySimpleGUI

328 views Asked by At

First let me preface this by saying that I have been reading through PySimpleGUI docs page and searched high and low on the web, but I can't seem to find a tutorial on how actually get a window to do stuff. I got the GUI basics down, but now I don't know how to insert the code in the window, so it actually does things.

I'm trying to create a basic distance converter (from miles to kilometers). The layout works and so does the function, but I have no clue on how to integrate both.

import PySimpleGUI as sg

layout = [[sg.Text("Enter miles"), sg.InputText(key='-IN-')],
          [sg.Text('Kilometers ->'),sg.Text(key='-OUT-')],
          [sg.Button('Calculate'),sg.Button('Exit')]]

window = sg.Window('Miles to Kilometers',layout)

while True:
    event,values = window.read()
    if event == 'Exit' or event == sg.WIN_CLOSED:
        break
    elif event == 'Calculate':
        window['-OUT-'].update(converter(values['-IN-']))

def converter():
    miles = int(input("Enter miles: "))
    res = miles * 1.609344
    print(round(res,2))
converter()

window.close()
1

There are 1 answers

3
MacItaly On BEST ANSWER

Couple of things I noticed...

(1) There is no space for the '-OUT-' text to be displayed. By creating a space with "\t\t\t" I've allowed the output a place to be printed.

(2) When 'Calculate' is pressed, it needs to call the function. You'll see I've changed the function converter() to receive the value entered by the user in the '-IN-' box.

import PySimpleGUI as sg

def converter(miles):
    res = miles * 1.609344
    return res


layout = [[sg.Text("Enter miles"), sg.InputText(key='-IN-')],
          [sg.Text('Kilometers ->'),sg.Text("\t\t\t", key='-OUT-')],
          [sg.Button('Calculate'),sg.Button('Exit')]]

window = sg.Window('Miles to Kilometers',layout)

while True:
    event,values = window.read()
    if event == 'Exit' or event == sg.WIN_CLOSED:
        break
    if event == 'Calculate':
        res = converter(float(values['-IN-']))
        window['-OUT-'].update(value=round(res,2))


window.close()

This should give you what you're looking for.