What I am trying to do with the following code is read from arduino serial and update a label with that data every few seconds.
When I run the code it only gets/updates the label once. So I know its something to do with a loop. My understanding was that all code between Tk()
and mainloop()
was in a loop. Any help would be appreciated.
from Tkinter import *
import serial
import time
def show_values():
arduinoSerialData.write("55")#Write some data to test Arduino read serial and turn on LED if it does
arduinoSerialData = serial.Serial('/dev/cu.usbmodem1461', 9600, timeout=None)
time.sleep(5) #Arduino Serial Reset Timeout
Joes = Tk()
Joes.wm_title("Read Serial")
myData= arduinoSerialData.readline()
temp = float(myData) #convert string to float store in var
templabel = Label(Joes, text=(temp))
templabel.pack()
c = Button(Joes, text="Send Data", command=show_values)
c.pack()
time.sleep(2)
Joes.mainloop()
It appears that you misunderstand how the TK mainloop works. It is not, as you described, a loop between calling Tk()
and mainloop()
, but rather within Tkinter, external of your programs code.
In order to have a loop, updating a label, you would have to specifically write a loop, using Tk's after
method, calling an iterable function over and over.
You could make a function like this to do what you want:
def update_label():
data= float(arduinoSerialData.readline())
templabel.config(text=str(data)) #Update label with next text.
Joes.after(1000, update_label)
#calls update_label function again after 1 second. (1000 milliseconds.)
I am unsure of how the arduino data is retrieved, so you may need to modify that slightly to have the correct data. This is a general premise though for creating a loop in the manner you described.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.