我正在尝试编写一个从串行端口连接获取数据并根据该数据实时自动更新 Tkinter 窗口的程序。
我尝试为窗口创建一个单独的线程,定期从主线程获取当前数据并更新窗口,如下所示:
serialdata = []
data = True
class SensorThread(threading.Thread):
def run(self):
serial = serial.Serial('dev/tty.usbmodem1d11', 9600)
try:
while True:
serialdata.append(serial.readline())
except KeyboardInterrupt:
serial.close()
exit()
class GuiThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.root = Tk()
self.lbl = Label(self.root, text="")
def run(self):
self.lbl(pack)
self.lbl.after(1000, self.updateGUI)
self.root.mainloop()
def updateGUI(self):
msg = "Data is True" if data else "Data is False"
self.lbl["text"] = msg
self.root.update()
self.lbl.after(1000, self.updateGUI)
if __name == "__main__":
SensorThread().start()
GuiThread().start()
try:
while True:
# A bunch of analysis that sets either data = True or data = False based on serialdata
except KeyboardInterrupt:
exit()
运行它会给我这个错误:
线程 Thread-2 中的异常:回溯(最后一次调用):文件“/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py”,第 522 行,在 __bootstrap_inner self. run() 文件“analysis.py”,第 52 行,在运行 self.lbl1.pack() 文件“/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter .py",第 1764 行,在 pack_configure + self._options(cnf, kw)) RuntimeError:主线程不在主循环中
当我在谷歌上搜索这个错误时,我大多会收到人们试图从两个不同的线程与窗口交互的帖子,但我认为我没有这样做。有任何想法吗?非常感谢!