How to update input element to display new set of values on an event? PySimpleGui

44 Views Asked by At

I have an app that converts units(example Cm to Inch, etc). One function I want the app to have is to be able to change the units its converting, right now it only converts certain length elements but I would like it to also be able to convert units of mass. I tried inplementing this by having a variable that stores the list of the specific units(mass_units = [...]) and then when the event switching the spin element to a different unit occurs the variable is equal to a different set of units.

Code:

import PySimpleGUI as sg
from convert import * #file for handling all conversions between units
    
output_value = 0 #output on 2nd input element
main_units = ["Length", "Mass"]#units for elements on 2nd row

length_units = ["Centimeter","Inch","Meter","Kilometer","Feet","Mile"]#units for length
mass_units = ["Gram", "Kilogram", "Pound", "Ounce", "Ton"] #units for mass

selected_unit = length_units

#create layout, giving each element a unique key
layout = [
    [sg.Text("CONVERTER APP")],
    [sg.Spin(main_units, key="main-units",enable_events=True)], #main units element
                                    
    [sg.Input(key="input", enable_events=True),sg.Spin(selected_unit, key="select-unit-1"),#3rd row(Divided in 2 to avoid overflow), first input and select unit element
    sg.Text("="),sg.Input(output_value, key="output", enable_events=True),sg.Spin(selected_unit, key="select-unit-2")], #second input and select unit element

    [sg.Button("Convert", key="convert-button")] #button element, convert first unit to value of second element
]

window = sg.Window("Converter App", layout) #initialize window

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

    if event == sg.WIN_CLOSED:
        break
    if event == 'covert-button' or 'input': #output converts values based on input
        try:
            input_value = float(values['input'])
            
            if values['select-unit-1'] == values['select-unit-2']:
                output_value = values['input']
                window['output'].update(values['input'])
            else:
                output_value = convert_lengths(values['input'], values['select-unit-1'], values['select-unit-2'])
                window['output'].update(output_value)
                print(values['input'], values['output'])
            
            if event == 'main-units':
                selected_unit = mass_units
                window.Element('select-unit-1').update(values=[selected_unit])

        #So app doesnt crash on value errors
        except ValueError:
            window['output'].update(0)
            print("Value Error")
                        
window.close()

1

There are 1 best solutions below

0
Jason Yang On

Update relative elements when event for the main unit happened.

Example Code

import PySimpleGUI as sg

table = {
    "Length": {
        "Centimeter": 1.0,
        "Inch": 2.54,
        "Meter": 100,
        "Kilometer": 100000.0,
        "Foot": 30.48,
        "Mile": 160934.4,
    },
    "Mass": {
        "Gram": 1.0,
        "Kilogram": 1000.0,
        "Pound": 453.59237,
        "Ounce": 28.349523125,
        "Ton": 1000000.0,
    }
}

kinds = sorted(list(table.keys()))
kind = kinds[0]
units = sorted(list(table[kind].keys()))

sg.theme("DarkBlue")
sg.set_options(font=("Courier New", 20))

left = [
    [sg.Input("0", size=10, expand_x=True, enable_events=True, key="IN 1")],
    [sg.Listbox(units, default_values=units[0], size=(15, 5), key="UNIT 1")],
]
right = [
    [sg.Input("0", size=10, expand_x=True, enable_events=True, key="IN 2")],
    [sg.Listbox(units, default_values=units[0], size=(15, 5), key="UNIT 2")],
]
layout = [
    [sg.Text("CONVERTER APP", justification='center', expand_x=True)],
    [sg.Push(),
     sg.Spin(kinds, initial_value=kind, size=(15, 1), enable_events=True, key="KIND"),
     sg.Push()],
    [sg.Column(left, pad=(0, 0)),
     sg.Text("=", expand_y=True),
     sg.Column(right, pad=(0, 0))],
    [sg.Button("Convert", expand_x=True)],
]

window = sg.Window("Converter App", layout)

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break
    elif event == "KIND":
        kind = values[event]
        units = sorted(list(table[kind].keys()))
        window["IN 1"].update("0")
        window["IN 2"].update("0")
        window["UNIT 1"].update(units, set_to_index=0)
        window["UNIT 2"].update(units, set_to_index=0)

window.close()

enter image description here enter image description here