broadcast_callback.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright 2021-2025 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. # Demonstrate how to update the value of a variable across multiple clients.
  17. # This application creates a thread that sets a variable to the current time.
  18. # The value is updated for every client when Gui.broadcast_change() is invoked.
  19. # -----------------------------------------------------------------------------------------
  20. from datetime import datetime
  21. from threading import Thread
  22. from time import sleep
  23. from taipy.gui import Gui
  24. # Update the 'current_time' state variable if 'update' is True
  25. def update_state(state, updated_time):
  26. if state.update:
  27. state.current_time = updated_time
  28. # The function that executes in its own thread.
  29. # Call 'update_state()` every second.
  30. def update_time(gui):
  31. while True:
  32. gui.broadcast_callback(update_state, [datetime.now()])
  33. sleep(1)
  34. current_time = datetime.now()
  35. update = False
  36. page = """
  37. Current time is: <|{current_time}|format=HH:mm:ss|>
  38. Update: <|{update}|toggle|>
  39. """
  40. if __name__ == "__main__":
  41. gui = Gui(page)
  42. # Run thread that regularly updates the current time
  43. thread = Thread(target=update_time, args=[gui], name="clock")
  44. thread.daemon = True
  45. thread.start()
  46. gui.run(title="Broadcast - Callback")