The line
If the GUI was to work with this code the
To get around this rather than using
Here is the code with the addition of after but I can't test it as I don't have the bme280, smbus2 etc
Note if the following lines
The following thread has information on not freezing the GUI:
[Tkinter] How to deal with code that blocks the mainloop, freezing the gui
root.mainloop()
is never reached because the code goes into an infinite loop from the while True:
up to the time.sleep(10)
If the GUI was to work with this code the
time.sleep
would freeze the GUI because mainloop
would not be able to update the GUI until the sleep
finishes.To get around this rather than using
time.sleep
, tkinter has an after
method that will call a function after a number of milliseconds.Here is the code with the addition of after but I can't test it as I don't have the bme280, smbus2 etc
import tkinter as tk import datetime import bme280 import smbus2 from smbus2 import SMBus from smbus import SMBus from bme280 import BME280 root = tk.Tk() root.title('Humidity Logger') root.configure(background='white') root.geometry("500x300") bus = SMBus(1) bme280 = BME280(i2c_dev=bus) bme_label = tk.Label(root, text = "bme280", fg = "green", bg = "white", font = ("Helvetica", 32)) bme_label.pack(pady = 35) def update(): now = datetime.datetime.now() temperature = bme280.get_temperature() humidity = bme280.get_humidity() pressure = bme280.get_pressure() tempf = float(temperature * 9.0 / 5.0) + 32.0 print(now.strftime("%m-%d-%Y %H:%M:%S") + ' | Temperature(*F/*C): {:.2f}*F | {:05.2f}*C | Humidity: {:05.2f}% | Pressure: {:05.2f}hPa'.format(tempf,temperature,humidity,pressure)) bme_label.configure(text='Temp(*F): {:.2f}*F | Humidity: {:05.2f}%'.format(tempf,temperature,humidity)) FileName = str("/home/pi/BME280_DataLog.txt") with open(FileName, "a") as f: f.write(now.strftime("%m-%d-%Y %H:%M:%S") + ' | Temperature(*F/*C): {:.2f}*F | {:05.2f}*C | Humidity: {:05.2f}% | Pressure: {:05.2f}hPa'.format(tempf,temperature,humidity,pressure) + '\n') root.after(10000, update) update() root.mainloop()
Note if the following lines
temperature = bme280.get_temperature() humidity = bme280.get_humidity() pressure = bme280.get_pressure()take a reasonable amount of time this will still freeze the GUI and will need to be done in a separate thread, see the link below for information.
The following thread has information on not freezing the GUI:
[Tkinter] How to deal with code that blocks the mainloop, freezing the gui