Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from queue import Queue
- from threading import Thread
- import tkinter
- #these three are just for the example and don't need to be in your real code.
- import random
- import time
- import datetime
- #this collection facilitates inter-thread communication.
- #the worker thread pushes status messages to it,
- #and the gui thread gets those messages and displays them.
- messages = Queue()
- def get_temperature():
- #pretend that this function gets the temperature from a thermometer peripheral or a weather website or something.
- return random.randint(40, 90)
- def check_temperature_forever():
- """
- Checks the temperature every second and pushes that data into the messages queue.
- This loops forever and never returns, so it's best run in its own thread.
- """
- while True:
- time.sleep(1)
- temp = get_temperature()
- message = "{} - the temperature is {} degrees F".format(datetime.datetime.now(), temp)
- messages.put(message)
- def on_idle():
- """whenever the window isn't busy with another task, see if there are any new messages to display."""
- #check for messages
- if not messages.empty():
- message = messages.get()
- #display the message
- label.config(text=message)
- #call this function again the next time the window isn't busy
- root.after_idle(on_idle)
- #set up window
- root = tkinter.Tk()
- label = tkinter.Label(root)
- label.pack()
- #start thread. use `daemon=True` if you want the thread to terminate when the user closes the window.
- t = Thread(target=check_temperature_forever, daemon=True)
- t.start()
- #wait until the window is ready to be displayed.
- #If we don't do this, then `on_idle` will call itself over and over forever,
- #because the window counts as "not busy" if it isn't visible yet.
- root.wait_visibility()
- #register idle event
- root.after_idle(on_idle)
- #start the GUI's event loop, which will never return as long as the window is open
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement