[英]Tkinter Python Continuously update Label from serial data?
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. 我要使用以下代码尝试从arduino序列读取数据,并每隔几秒钟用该数据更新标签。
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. 我的理解是
Tk()
和mainloop()
之间的所有代码都在一个循环中。 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. 看来您误解了TK mainloop的工作原理。 It is not, as you described, a loop between calling
Tk()
and mainloop()
, but rather within Tkinter, external of your programs code. 正如您所描述的,它不是在调用
Tk()
和mainloop()
之间的循环,而是在Tkinter中,程序代码的外部。
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. 为了有一个循环,更新标签,您必须专门使用Tk的
after
方法编写一个循环,一遍又一遍地调用一个可迭代的函数。
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. 我不确定如何获取arduino数据,因此您可能需要稍作修改以获取正确的数据。 This is a general premise though for creating a loop in the manner you described.
尽管这是按您描述的方式创建循环的一般前提。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.