1
votes

Newbie to Python, started off messing with a DHT11 Temp/Humidity Sensor, a Raspberry Pi 3, and Python 3.

I am using the standard Adafruit DHT11 Library for Python.

Reading from GPIO 27

I am able to display the temperature in a GUI window just fine. What I am stuck on is how to have the GUI update/refresh the temperature at a set rate so it is a "live" display of the current temperature. Right now, I can only get changes from the GUI if I close and reopen my script. See my code below:

    from tkinter import *
    import tkinter.font
    import Adafruit_DHT

    temp = 0

    win = Tk()
    win.title("Temperature")
    win.geometry("100x100")

    def READ():
        global temp
        humidity, temperature = Adafruit_DHT.read_retry(11, 27)
        temp = temperature * 9/5.0 + 32
        Label (win, text=str(temp), fg="black", bg="white", font="36").grid(row=0, column=0)

    if (temp >= 0):
        READ()

    mainloop()
1

1 Answers

1
votes

Create the Label once at the start of the program, and save a reference:

the_label = Label (win, text="", fg="black", bg="white", font="36")
the_label.grid(row=0, column=0)

Next, create a function that gets the value and updates the label:

def READ():
    global temp
    humidity, temperature = Adafruit_DHT.read_retry(11, 27)
    temp = temperature * 9/5.0 + 32
    the_label.configure(text=str(temp))

Next, create a new function that calls this function, and then schedules itself t be called again after a delay:

def read_every_second():
    READ()
    root.after(1000, read_every_second)

Finally, call read_every_second once at the start of your program. It will then run until your program exits.