Tkinter Python从串行数据持续更新标签?

2024-09-28 21:58:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我要做的是从arduino序列号读取以下代码,并每隔几秒钟用这些数据更新一个标签。在

当我运行代码时,它只获取/更新一次标签。所以我知道这和循环有关。我的理解是Tk()和{}之间的所有代码都在一个循环中。任何帮助都将不胜感激。在

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()

Tags: to代码importtimeshowserialsleep标签
1条回答
网友
1楼 · 发布于 2024-09-28 21:58:03

看来您误解了TK主循环的工作方式。正如您所描述的,它不是调用Tk()mainloop()之间的循环,而是在程序代码外部的Tkinter中。在

为了有一个循环,更新一个标签,你必须专门编写一个循环,使用Tk的after方法,反复调用iterable函数。在

您可以创建这样一个函数来执行您想要的操作:

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数据,因此您可能需要稍微修改一下以获得正确的数据。 这是按照您描述的方式创建循环的一般前提。在

相关问题 更多 >