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