Tkinter Python不断从串行数据更新Label吗? [英] Tkinter Python Continuously update Label from serial data?
问题描述
我试图从arduino串行读取以下代码,并每隔几秒钟用该数据更新一个标签.
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.
当我运行代码时,它只会获取/更新一次标签.因此,我知道它与循环有关.我的理解是Tk()
和mainloop()
之间的所有代码都处于循环中.任何帮助将不胜感激.
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()
推荐答案
似乎您误解了TK mainloop的工作方式.正如您所描述的,它不是在调用Tk()
和mainloop()
之间的循环,而是在程序代码外部的Tkinter中.
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.
为了拥有一个循环,更新标签,您必须使用Tk的after
方法专门编写一个循环,一遍又一遍地调用一个可迭代的函数.
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.)
我不确定如何获取arduino数据,因此您可能需要稍作修改以获取正确的数据. 尽管这是按您描述的方式创建循环的一般前提.
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.
这篇关于Tkinter Python不断从串行数据更新Label吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!