Dynamiczne aktualizowanie okna Tkinter na podstawie danych szeregowych
Próbuję napisać program, który pobiera dane z połączenia portu szeregowego i automatycznie aktualizuje okno Tkinter w czasie rzeczywistym na podstawie tych danych.
Próbowałem utworzyć osobny wątek dla okna, które okresowo pobiera bieżące dane z głównego wątku i aktualizuje okno, tak jak poniżej:
<code>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() </code>
Uruchomienie powoduje ten błąd:
Wyjątek w wątku Thread-2: Traceback (ostatnie ostatnie wywołanie): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", wiersz 522, w __bootstrap_inner self. run () Plik "analysis.py", wiersz 52, w run self.lbl1.pack () Plik "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter .py ", linia 1764, w pack_configure + self._options (cnf, kw)) RuntimeError: główny wątek nie jest w głównej pętli
Kiedy google to błąd, najczęściej dostaję posty, w których ludzie próbują współdziałać z oknem z dwóch różnych wątków, ale nie sądzę, żebym to robił. Jakieś pomysły? Dzięki wielkie!