Python Forum
TKinter Not Executing
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TKinter Not Executing
#2
The line 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
Nu2Python likes this post
Reply


Messages In This Thread
TKinter Not Executing - by Nu2Python - Jan-05-2023, 10:24 PM
RE: TKinter Not Executing - by Yoriz - Jan-05-2023, 11:42 PM
RE: TKinter Not Executing - by Nu2Python - Jan-06-2023, 03:56 PM
RE: TKinter Not Executing - by Vadanane - Jan-31-2023, 10:04 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020