Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Updating labels
#1
Hello,

I am trying to make a Gui with 2 labels that shows the live measurements of the sensors(DS18B20) that I have attached to a raspberry. The problem is that it wont't update the values it just shows the first values it has measured.
I hope someone can help me,
thanks in advance


this is the code that I am using.

root = tk.Tk()
canvas = tk.Canvas(root, width=600, height=420, background="Black")
canvas.pack()
canvas.create_image(400, 240)

sensor1, sensor2 = W1ThermSensor.get_available_sensors()

temperatuur = sensor1.get_temperature()
temperatuur2 = sensor2.get_temperature()

Label3 = Label(text=temperatuur)
Label3_window = canvas.create_window(100, 100, anchor="nw", window=Label3)

Label4 = Label(text=temperatuur2)
Label4_window = canvas.create_window(200, 200, anchor="nw", window=Label4)


root.mainloop()
Reply
#2
Please post W1ThermSensor code, (and anything else required) so script can be run.
Reply
#3
Working example with a mock sensor.
But I think drawing the values in a canvas is not the best solution.


from random import uniform
from tkinter import Button, Canvas, Label, Tk, Variable


class MockSensor:
    """
    Class to immitate your sensor
    """

    @staticmethod
    def get_temperature():
        return uniform(10, 40)


def update(root, temp_var1, temp_var2, sensor1, sensor2):
    tmp1 = sensor1.get_temperature()
    tmp2 = sensor2.get_temperature()
    temp_var1.set(f"{tmp1:.1f} °C")
    temp_var2.set(f"{tmp2:.1f} °C")
    # this function is called later by mainloop
    # after 1000 ms
    root.after(1000, update, root, temp_var1, temp_var2, sensor1, sensor2)


root = Tk()
root.title("Mock Temperature")
canvas = Canvas(root, width=600, height=420, background="Black")
canvas.pack()
canvas.create_image(400, 240)

# sensor1, sensor2 = W1ThermSensor.get_available_sensors()
sensor1 = sensor2 = MockSensor()
# fake sensor
temp_variable1 = Variable(root)
temp_variable2 = Variable(root)

canvas.create_window(100, 100, anchor="nw", window=Label(textvariable=temp_variable1))
canvas.create_window(200, 200, anchor="nw", window=Label(textvariable=temp_variable2))

# exit button
Button(root, text="Exit", command=root.destroy).pack()

# start first time update
root.after(0, update, root, temp_variable1, temp_variable2, sensor1, sensor2)

root.mainloop()
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

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