Reputation: 13
Fisrt of all i want to say that i am new in python I am trying to get the temperature value of a BME280 sensor and display it into a label widget via tkinter.
Here is my sample code:
import board
from tkinter import *
import busio
import adafruit_bme280
i2c = busio.I2C(board.SCL, board.SDA)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
main = Tk()
main.geometry('480x320')
main.configure(background = 'black')
main.title('Temperature Reading')
tempvar = StringVar()
tempvar.set("Temperature: " + str(bme280.temperature) + chr(32) + chr(176) + "C")
templbl = Label(main,
relief = GROOVE,
bd = 6,
padx = 10,
bg="blue",
fg="yellow",
font=('Mistral 14 bold'),
textvariable = tempvar)
templbl.pack()
main.mainloop()
The problem is that the data displayed in the label does not change. I think that my code does not retreive temperature data from the sensor. My will is to read the temperature data every 30 seconds and display them into label. How can i update the displayed data in the label when the sensor's data changed?
Thanks in advance for your help. Yannis
Upvotes: 1
Views: 196
Reputation: 631
This is your code updated
import board
from tkinter import *
import busio
import adafruit_bme280
i2c = busio.I2C(board.SCL, board.SDA)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
main = Tk()
main.geometry('480x320')
main.configure(background = 'black')
main.title('Temperature Reading')
tempvar = StringVar()
templbl = Label(main,
relief = GROOVE,
bd = 6,
padx = 10,
bg="blue",
fg="yellow",
font=('Mistral 14 bold'),
textvariable = tempvar)
templbl.pack()
def update_temp():
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
tempvar.set("Temperature: " + str(bme280.temperature) + chr(32) + chr(176) + "C")
main.after(30000, update_temp)
main.after(30000, update_temp)
main.mainloop()
Upvotes: 1