1

I am trying to make my variable on my label update, however have encountered a problem where the function of the buttons works by changing the temperature set up and down by 0.5 deg C however the labels on the temp and desired temp will not change with it.

I am working in python3.6

Here is my code, I was wondering if anyone may be able to help me please?

import os
import glob
import time
import RPi.GPIO as GPIO
from datetime import datetime


#Set gpio's
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17,GPIO.OUT)#RED
GPIO.setup(22,GPIO.OUT)#GREEN
GPIO.setup(27,GPIO.OUT)#BLUE


#grab temp probe information
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'


# Read temperature from device

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines=read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.1)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000
        #temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c#, temp_f


temp = read_temp()
desiredtemp = 17
deg = u'\xb0'#utf code for degree


def increase():
    global desiredtemp
    desiredtemp = desiredtemp + 0.5
    print(desiredtemp)

def decrease():
    global desiredtemp
    desiredtemp = desiredtemp - 0.5
    print(desiredtemp)


#Tkinter start

from tkinter import *
root = Tk()
#code to add widgets will go here....

topFrame = Frame(root)
topFrame.pack(side=TOP)

middleFrame = Frame(root)
middleFrame.pack()

bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)

#Set buttons
button1 = Button(bottomFrame, text="Increase (0.5"+ deg +"C)", fg="black", command=increase)
button2 = Button(bottomFrame, text="Decrease (0.5"+ deg +"C)", fg="black", command=decrease)


#use to put buttons on screen
button1.pack(side=LEFT)
button2.pack(side=LEFT)


#Set labels
label1 = Label(topFrame, text="Desired Temp = ", fg="black")
label2 = Label(middleFrame, text="Actual Temp = ", fg="black")
label3 = Label(topFrame, text=desiredtemp, fg="black")
label4 = Label(middleFrame, text=temp, fg="black")


#use to put labels on screen
label1.pack(side=LEFT)
label2.pack(side=LEFT)
label3.pack(side=LEFT)
label4.pack(side=LEFT)



root.mainloop()

#Tkinter End


# Open file to be logged

file = open("/home/pi/Desktop/Templog.csv", "a")

if os.stat("/home/pi/Desktop/Templog.csv").st_size == 0:
    file.write("Date, Time, TemperatureSensor1\n")




# Continuous print loop
while True:
    print(read_temp())
    if(read_temp()<desiredtemp):
       GPIO.output(17,GPIO.LOW)
       GPIO.output(22,GPIO.HIGH)

    else:
       GPIO.output(17,GPIO.HIGH)
       GPIO.output(22,GPIO.LOW)

    now = datetime.now()
    file.write(str(now.day)+"-"+str(now.month)+"-"+str(now.year)+","+str(now.hour)+":"+str(now.minute)+":"+str(now.second)+","+str(read_temp())+"\n")
    file.flush()
    time.sleep(1)
Pang
  • 9,564
  • 146
  • 81
  • 122

1 Answers1

0

You can use StringVar to associate a string variable with a Label widget. You pass the StringVar to the Label as the textvariable keyword argument and in each button callback simply update the value of the temperature and the StringVar using its set method.

Example extending your own code:

import os
import glob
import time

from datetime import datetime
from tkinter import *

temp = 18
desiredtemp = 17
deg = u'\xb0'    # utf code for degree


def increase():
    global desiredtemp
    desiredtemp += 0.5
    tmpstr.set("%s" % desiredtemp)


def decrease():
    global desiredtemp
    desiredtemp -= 0.5
    tmpstr.set("%s" % desiredtemp)

root = Tk()

topFrame = Frame(root)
topFrame.pack(side=TOP)

middleFrame = Frame(root)
middleFrame.pack()

bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)

button1 = Button(bottomFrame, text="Increase (0.5"+ deg +"C)", fg="black", command=increase)
button2 = Button(bottomFrame, text="Decrease (0.5"+ deg +"C)", fg="black", command=decrease)

button1.pack(side=LEFT)
button2.pack(side=LEFT)

tmpstr = StringVar(value="%s" % desiredtemp)

label1 = Label(topFrame, text="Desired Temp = ", fg="black")
label2 = Label(middleFrame, text="Actual Temp = ", fg="black")
label3 = Label(topFrame, textvariable=tmpstr, fg="black")
label4 = Label(middleFrame, text=temp, fg="black")

label1.pack(side=LEFT)
label2.pack(side=LEFT)
label3.pack(side=LEFT)
label4.pack(side=LEFT)

root.mainloop()

Note that use of the global keyword is generally considered a code smell, which should make you consider placing all those elements into a class.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • Thank you for your help, this has worked :) please may you explain the use of ("%s" % desiredtemp) and how this works? Or point me in the direction of where I can read about the use of this code. – Josh Bannister Apr 04 '17 at 06:12
  • Sure it's just string formatting. The more modern way is to use the `format` method of a string e.g. `'{}'.format(desiredtemp)`. I'm maybe a little old school using `%`, but to a basic level it does the same thing. See https://pyformat.info/ for some pretty comprehensive info on the subject. – Paul Rooney Apr 04 '17 at 06:14
  • Thank you, I will take a look at that. I am assuming that in order to make temp = read_temp() update my label I have to use crtmpstr = StringVar(value="%s" % temp) and replace temp in my label with crtmpstr? – Josh Bannister Apr 04 '17 at 06:15
  • I'm not 100% certain what you are asking but. You should only need a single StringVar. You should capture the input from `read_temp` and set it's string formatted value into the `StringVar` associated with the label. – Paul Rooney Apr 04 '17 at 06:19
  • Hi Paul, I just found out I have another problem also, my `root.mainloop()` does not include my `while True:` loop (which is controlling the temperature), when I include the while loop in he main loop and add a `root.update()` to the while loop it lags heavily – Josh Bannister Apr 04 '17 at 07:01
  • @JoshBannister it's best to create another question tailored specifically to that issue. It's difficult to tell without seeing the updated code, but please don't edit this question. You will get an increased chance for gaining rep by asking more, less specific questions also the question you have may already be [answered elsewhere](http://stackoverflow.com/questions/459083/how-do-you-run-your-own-code-alongside-tkinters-event-loop) . – Paul Rooney Apr 04 '17 at 07:07
  • Thanks for the tip, here is my new question http://stackoverflow.com/questions/43200770/python-while-loop-within-mainloop-causing-lag – Josh Bannister Apr 04 '17 at 07:25