builder.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. # -----------------------------------------------------------------------------------------
  12. # To execute this script, make sure that the taipy-gui package is installed in your
  13. # Python environment and run:
  14. # python <script>
  15. # -----------------------------------------------------------------------------------------
  16. import pandas as pd
  17. import taipy.gui.builder as tgb
  18. from taipy.gui import Gui, State
  19. categories = ["Real Estate", "Stocks", "Cash", "Retirement", "Other"]
  20. amounts = [190000, 60000, 100000, 110000, 40000]
  21. # Return an array where each item represents the percentage of the corresponding value in the
  22. # input array:
  23. # [10, 10] -> [50, 50]
  24. # [1, 2, 3] -> [16, 33, 50]
  25. def compute_ratio(amounts: list[int]) -> list[int]:
  26. total = sum(amounts)
  27. return [int((amount / total) * 100) for amount in amounts]
  28. # Initialize the ratio array
  29. ratio = compute_ratio(amounts)
  30. # Create the dataset used by the table
  31. data = pd.DataFrame({"Category": categories, "Amount": amounts, "%": ratio})
  32. # Called when the user edits a cell's value
  33. def update(state: State, var_name: str, payload: dict):
  34. # Batch the updates to the state
  35. with state:
  36. # Invoke the default processing for 'on_edit'
  37. # Because the table data is a Pandas data frame, the cell is updated automatically
  38. state.get_gui().table_on_edit(state, var_name, payload)
  39. # Update ratios based on the new cell value
  40. state.data["%"] = compute_ratio(state.data["Amount"])
  41. # Update the control
  42. state.refresh(var_name)
  43. with tgb.Page() as page:
  44. tgb.table("{data}", editable__Amount=True, on_edit=update, on_add=False, on_delete=False, show_all=True)
  45. if __name__ == "__main__":
  46. Gui(page).run(title="Table - Action on edit")