我想編寫一個程序,從串行端口連接獲取數據,並自動根據這些數據實時更新的Tkinter窗口動態更新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()
運行它給我這個錯誤:
Exception in thread Thread-2: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner self.run() File "analysis.py", line 52, in run self.lbl1.pack() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1764, in pack_configure + self._options(cnf, kw)) RuntimeError: main thread is not in main loop
當我谷歌這個錯誤,我主要是在人們試圖從兩個不同的線程與窗口交互的帖子,但我不認爲我這樣做。有任何想法嗎?非常感謝!
你有沒有嘗試在一個線程中運行TK部分?即只是在一個線程中運行串口端口的東西,傳統知識的東西可以留在主流程中。我懷疑這可能會工作... –
就像一個線程獲取串行端口數據和另一個線程的數據分析循環?我會給你一個鏡頭。 – user1363445