Source code for module_that_can_invoke_gui_from_cli

  1"""Calculate arithmetic expressions from GUI."""
  2
  3import pydantic
  4import PySimpleGUI
  5
  6import package_name_to_import_with
  7
  8FIRST_NUMBER_INPUT = "first_number"
  9SECOND_NUMBER_INPUT = "second_number"
 10OPERATOR_INPUT = "operator"
 11OPERATION_RESULT = "result"
 12CLOSE_BUTTON = "Close"
 13
 14
[docs] 15@pydantic.validate_call(validate_return=True) 16def define_gui_layout() -> list[list[pydantic.InstanceOf[PySimpleGUI.Element]]]: 17 """Prepare design of the GUI. 18 19 Returns 20 ------- 21 list[list[PySimpleGUI.Element]] 22 elements of the GUI 23 """ 24 layout = [ 25 [PySimpleGUI.Text("Enter first number"), PySimpleGUI.Input(key=FIRST_NUMBER_INPUT)], 26 [ 27 PySimpleGUI.Text("Enter operator"), 28 PySimpleGUI.OptionMenu( 29 package_name_to_import_with.calculator_sub_package.BinaryArithmeticOperator, 30 key=OPERATOR_INPUT, 31 ), 32 ], 33 [PySimpleGUI.Text("Enter second number"), PySimpleGUI.Input(key=SECOND_NUMBER_INPUT)], 34 [PySimpleGUI.Button(button_text="Submit")], 35 [PySimpleGUI.Text("Operation Result", key=OPERATION_RESULT)], 36 [PySimpleGUI.Button(button_text=CLOSE_BUTTON)], 37 ] 38 39 return layout
40 41
[docs] 42@pydantic.validate_call(validate_return=True) 43def define_gui_window( 44 gui_layout: list[list[pydantic.InstanceOf[PySimpleGUI.Element]]], 45) -> pydantic.InstanceOf[PySimpleGUI.Window]: 46 """Create GUI with provided design. 47 48 Parameters 49 ---------- 50 gui_layout : list[list[PySimpleGUI.Element]] 51 design of the GUI 52 53 Returns 54 ------- 55 PySimpleGUI.Window 56 designed GUI 57 """ 58 window = PySimpleGUI.Window("GUI Calculator", layout=gui_layout) 59 60 return window
61 62
[docs] 63@pydantic.validate_call(validate_return=True) 64def orchestrate_interaction(gui_window: pydantic.InstanceOf[PySimpleGUI.Window]) -> None: 65 """Control flow of the GUI. 66 67 Parameters 68 ---------- 69 gui_window : PySimpleGUI.Window 70 designed GUI 71 """ 72 while True: 73 gui_event, gui_elements = gui_window.read() # pyright: ignore [reportGeneralTypeIssues] 74 75 if PySimpleGUI.WINDOW_CLOSED or gui_event == CLOSE_BUTTON: 76 break 77 78 try: 79 operation_result = package_name_to_import_with.calculate_results( 80 gui_elements[FIRST_NUMBER_INPUT], 81 gui_elements[OPERATOR_INPUT], 82 gui_elements[SECOND_NUMBER_INPUT], 83 ) 84 except Exception as error: # noqa: BLE001 # pylint: disable=broad-except 85 gui_window[OPERATION_RESULT].update(value=str(error)) 86 else: 87 gui_window[OPERATION_RESULT].update(value=operation_result)
88 89
[docs] 90@pydantic.validate_call(validate_return=True) 91def gui_calculator() -> None: 92 """Calculate arithmetic expressions.""" 93 gui_layout = define_gui_layout() 94 gui_window = define_gui_window(gui_layout) 95 96 try: 97 orchestrate_interaction(gui_window) 98 finally: 99 gui_window.close()
100 101 102if __name__ == "__main__": 103 gui_calculator()