Click here to Skip to main content
14,970,219 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Im trying to display the real time temperature of the sensor on the GUI, Im able to get different temperatures and updated temperaure in the console but when I link it to a label in the GUI, it does not update, it only updates for the first time and displays the 1st temperature but unlike the console, I can not see it being updated every 2 seconds.

from socket import *
import time
import tkinter as tk


 
class UpdateLabel():
    def __init__(self):
        self.master = tk.Tk()
        self.label1_text = tk.StringVar()
        self.label1_text.set("initial value")
        self.label1=tk.Label(self.master, textvariable=self.label1_text,
                            fg='blue', font=("Arial", 36, "bold"),
                            background='#CDC5D9')
        self.label1.grid(row=0,column=0)
 
        self.master.grid_columnconfigure(1, minsize=100)
 
      
 
        tk.Button(self.master, text="Quit", command=self.master.quit,
                  bg="red").grid(row=1, column=0)
 
        ## update the label in two different ways
        self.master.after(2000, self.update_label_1) ## sleep for 2 seconds
 
        self.master.mainloop()
 
    def update_label_1(self):

        self.label1_text.set(temp)

 

 
address= ( '192.168.1.170', 5000) #define server IP and port
client_socket =socket(AF_INET, SOCK_DGRAM) #Set up the Socket
client_socket.settimeout(1) #Only wait 1 second for a response



 
while(1):
 
    data = "Temperature".encode() #Set data request to Temperature
 
    client_socket.sendto( data, address) #Send the data request
 
    try:
 
        rec_data, addr = client_socket.recvfrom(2048) #Read response from arduino
        temp = float(rec_data) #Convert string rec_data to float temp
        
        
        print ("The Measured Temperature is ", temp, " °C.") # Print the result
        
        UpdateLabel()
    
 
    except:
        pass
    
 
 
 
    time.sleep(2) #delay before sending next command
    
    if temp >25:
        
        data = "LEDON".encode() #Set data request to Pressure
         
        client_socket.sendto( data, address) #Send the data request
        
        
    if temp <25:
        
        data = "LEDOFF".encode() #Set data request to Pressure
         
        client_socket.sendto( data, address) #Send the data request
         
       
 
    time.sleep(2) #delay before sending next command


What I have tried:

I receive the updated temperature from the server(arduino) after I request the temerature from the client(Python) and I store and display it as temp, which works perfectly when on the console, however unable to update the label. Thank you
Posted
Updated 19-Jan-21 22:41pm

1 solution

Python
UpdateLabel()

You forgot to pass the temp value to the UpdateLabel function. It should be:
Python
update_label_1(temp)


[edit]
Corrected the function name.
[/edit]


[edit version="2"]
I have reviewed your code and the issue is slightly more complicated. The reason that the label never gets update is because the while loop is blocking the GUI and so preventing any changes. There are two ways to resolve this:
1. Run the temperature capture code in a background thread, thus allowing the GUI to update the window.
2. Move all the code into the GUI class so it runs itself.

Option 2 is the simplest to implement, and the following code can form the basis of what you need.
Python
import time
import random
import tkinter as tk


class TempView(tk.Frame):
    def __init__(self, master):
        super().__init__(master)     # call base class
        self.label1_text = tk.StringVar()
        self.label1_text.set("initial value")
        self.label1=tk.Label(self.master, textvariable=self.label1_text,
                            fg='blue', font=("Arial", 18, "bold"),
                            background='#CDC5D9')
        self.label1.grid(row=0,column=0)
 
        self.master.grid_columnconfigure(1, minsize=100)
 
        tk.Button(self.master, text="Quit", command=self.master.destroy,
                  bg="red").grid(row=1, column=0)
 
        ## update the label in two different ways
        self.getTemp()
    
    def getTemp(self):
        temp = str(random.randint(10, 100))
        self.update(temp)
        self.master.after(2000, self.getTemp) ## sleep for 2 seconds
 
    def update(self, temp):
        self.label1_text.set(temp)
        print(F"The temperature is {temp}")

random.seed()
root = tk.Tk()
app = TempView(master=root)
app.mainloop()

I have used the random class to capture some values, just as a sample. You need to change the getTemp method to get the actual values from your device.

[/edit]
   
v3
Comments
Member 14589606 20-Jan-21 4:59am
   
I passed temp and now the GUI does not pop up, it pop ups when I dont pass temp and when I dont pass temp, it only displays the 1st temperature
Richard MacCutchan 20-Jan-21 5:23am
   
Yes because you are calling the class instead of the update method. You need to define your object names better.
Member 14589606 20-Jan-21 6:14am
   
Thank you for your reply. I tried passing the arguments through the function and tried calling them but it does not work, it does not open any widget. Any ideas? Thanks
Richard MacCutchan 20-Jan-21 6:19am
   
I tried your code (without the UDP calls) but I could not get it to work. But I am not an expert in Tcl/Tk, so am not sure what the issue is.
Member 14589606 20-Jan-21 6:34am
   
Hmm, strange. Thanks though
Richard MacCutchan 20-Jan-21 7:23am
   
See my update above.
Member 14589606 21-Jan-21 6:06am
   
Thank you very much, it worked. Can you let me know how I can add an input box and use the value somewhere, I added the box but was unable to use the input elsewhere. Thank you again for the help. Regards
Richard MacCutchan 21-Jan-21 7:30am
   
You just need to add a Text widget somewhere and capture its contents at the time that you need to process it. Google will find you lots of sample code. The important thing to remember in running a tkinter application is that everything happens in the GUI so all the code needs to run inside the class that creates the Window. You can have other separate modules, but they need to be called from within the class.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900