Вывод непрерывного потока данных с COM порта в интерфейс. Как вывести предыдущие значения
Есть очередь для одновременной работы com порта и интерфейса в tkinter. Данные непрерывно обновляются в интерфейсе. Я бы хотел реализовать запись двух предыдущих значений из очереди в entry Tkinter'a. Пока не смог разобраться как это сделать. Что-то нашел по поводу queue.pop, но рабочий вариант получить не удалось. Возможно ли получить доступ к списку этой очереди и при ее движении, забирать с первых трех позиций этого списка эти цифры? Код следующий:
import tkinter
import time
import threading
import random
import queue
import serial
class GuiPart:
def __init__(self, master, queue, endCommand, thread1):
self.queue = queue
button = tkinter.Button(text="Подключить", command=thread1) # threading.Thread(target=values).start()
button.pack()
#a="a bd"
# Set up the GUI
self.text = tkinter.StringVar()
self.text1 = tkinter.StringVar()
entry_2 = tkinter.Entry(root, textvariable=self.text)
entry_1 = tkinter.Entry(root, textvariable=self.text1)
explanation = tkinter.Label(root, text='Т:')
explanation.pack()
entry_2.pack()
entry_1.pack()
# Enter Selection
print(thread1)
# Add more GUI stuff here depending on your specific needs
console = tkinter.Button(master, text='Done', command=endCommand)
console.pack()
def processIncoming(self):
#"""Handle all messages currently in the queue, if any."""
while self.queue.qsize():
try:
msg = self.queue.get(0)
#msg[msg-1] = self.queue.get(0)
self.text.set(msg)
#self.text1.set(mnk)
#self.text1.set(msg)
# self.text1.set(msg-1)
# Check contents of message and do whatever is needed. As a
# simple test, print it (in real life, you would
# suitably update the GUI's display in a richer fashion).
#print(msg)
except queue.Empty:
# just on general principles, although we don't
# expect this branch to be taken in this case
pass
class ThreadedClient:
"""
Launch the main part of the GUI and the worker thread. periodicCall and
endApplication could reside in the GUI part, but putting them here
means that you have all the thread controls in a single place.
"""
def __init__(self, master):
"""
Start the GUI and the asynchronous threads. We are in the main
(original) thread of the application, which will later be used by
the GUI as well. We spawn a new thread for the worker (I/O).
"""
self.master = master
# Create the queue
self.queue = queue.Queue()
# Set up the GUI part
#self.gui = GuiPart(master, self.queue, self.endApplication)
# Set up the thread to do asynchronous I/O
# More threads can also be created and used, if necessary
self.running = 1
self.thread1 = threading.Thread(target=self.workerThread1)
self.thread1.start()
self.gui = GuiPart(master, self.queue, self.endApplication, self.thread1)
# Start the periodic call in the GUI to check if the queue contains
# anything
self.periodicCall()
def periodicCall(self):
"""
Check every 200 ms if there is something new in the queue.
"""
self.gui.processIncoming( )
if not self.running:
# This is the brutal stop of the system. You may want to do
# some cleanup before actually shutting it down.
import sys
sys.exit(1)
self.master.after(200, self.periodicCall)
def workerThread1(self):
"""
This is where we handle the asynchronous I/O. For example, it may be
a 'select( )'. One important thing to remember is that the thread has
to yield control pretty regularly, by select or otherwise.
"""
while self.running:
# To simulate asynchronous I/O, we create a random number at
# random intervals. Replace the following two lines with the real
# thing.
port = serial.Serial(
port='COM4',
baudrate='1200',
bytesize=8,
stopbits=1,
timeout=None)
while True:
#size=13
#msg.zfill(13)
msg = port.readline()
if len(msg) == 13:
if msg[len(msg)-1] == '/n':
if msg[2] == '4E':
if msg[len(msg)-2] == '/r':
msg = port.read(size=13)
msg = msg.decode('ASCII')
self.queue.put(msg)
#self.queue.put(msg-1)
#self.queue.put(msg - 2)
def endApplication(self):
self.running = 0
root = tkinter.Tk()
root.title("Магнитометр")
client = ThreadedClient(root)
root.mainloop()