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()


event == 'covert-button' or 'input'will always be True. I think what you need isevent in ('convert-button', 'input')instead (note thatcovert-buttonshould beconvert-buttoninstead). Alsoif event == 'main-units':block should not be insideif event == 'covert-button' or 'input':block.