Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. from queue import Queue
  2. from threading import Thread
  3. import tkinter
  4.  
  5. #these three are just for the example and don't need to be in your real code.
  6. import random
  7. import time
  8. import datetime
  9.  
  10. #this collection facilitates inter-thread communication.
  11. #the worker thread pushes status messages to it,
  12. #and the gui thread gets those messages and displays them.
  13. messages = Queue()
  14.  
  15. def get_temperature():
  16. #pretend that this function gets the temperature from a thermometer peripheral or a weather website or something.
  17. return random.randint(40, 90)
  18.  
  19. def check_temperature_forever():
  20. """
  21. Checks the temperature every second and pushes that data into the messages queue.
  22. This loops forever and never returns, so it's best run in its own thread.
  23. """
  24. while True:
  25. time.sleep(1)
  26. temp = get_temperature()
  27. message = "{} - the temperature is {} degrees F".format(datetime.datetime.now(), temp)
  28. messages.put(message)
  29.  
  30. def on_idle():
  31. """whenever the window isn't busy with another task, see if there are any new messages to display."""
  32.  
  33. #check for messages
  34. if not messages.empty():
  35. message = messages.get()
  36. #display the message
  37. label.config(text=message)
  38.  
  39. #call this function again the next time the window isn't busy
  40. root.after_idle(on_idle)
  41.  
  42. #set up window
  43. root = tkinter.Tk()
  44. label = tkinter.Label(root)
  45. label.pack()
  46.  
  47. #start thread. use `daemon=True` if you want the thread to terminate when the user closes the window.
  48. t = Thread(target=check_temperature_forever, daemon=True)
  49. t.start()
  50.  
  51. #wait until the window is ready to be displayed.
  52. #If we don't do this, then `on_idle` will call itself over and over forever,
  53. #because the window counts as "not busy" if it isn't visible yet.
  54. root.wait_visibility()
  55.  
  56. #register idle event
  57. root.after_idle(on_idle)
  58.  
  59. #start the GUI's event loop, which will never return as long as the window is open
  60. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement