broadcast_callback.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. # 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. current_time = datetime.now()
  25. update = False
  26. # Update the 'current_time' state variable if 'update' is True
  27. def update_state(state, updated_time):
  28. if state.update:
  29. state.current_time = updated_time
  30. # The function that executes in its own thread.
  31. # Call 'update_state()` every second.
  32. def update_time(gui):
  33. while True:
  34. gui.broadcast_callback(update_state, [datetime.now()])
  35. sleep(1)
  36. page = """
  37. Current time is: <|{current_time}|format=HH:mm:ss|>
  38. Update: <|{update}|toggle|>
  39. """
  40. gui = Gui(page)
  41. # Run thread that regularly updates the current time
  42. thread = Thread(target=update_time, args=[gui], name="clock")
  43. thread.daemon = True
  44. thread.start()
  45. gui.run()