1

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

  • Are you 100% sure its the label? Its worth repeatedly printing your variable to the console to double check incase your thermometer is the issue. Otherwise you can use [stringVar](https://stackoverflow.com/questions/1918005/making-python-tkinter-label-widget-update) – dwb Jul 11 '20 at 14:34
  • 1
    Use `after()` to periodically call `tempvar.set(...+str(bme280.temperature)+...)`. – acw1668 Jul 11 '20 at 14:50
  • Can you please give me and example on how to use after()? – Yannis Xidianakis Jul 11 '20 at 15:37
  • The problem is that i don't know how to check the sensor value every x seconds. The sensor works fine I i tried it with the print function in another test and it prints the data on Shell). This is the code i used for testing the sensor: – Yannis Xidianakis Jul 11 '20 at 16:00

1 Answers1

1

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()
Eric Mathieu
  • 631
  • 6
  • 11