в прилагаемой программе я пытаюсь получить некоторые данные через последовательный порт, а затем записать и построить их. Я планирую использовать независимые темы для чтения, записи и печати. Чтение и запись работает нормально, но я не смог добиться синхронного отображения поступающих данных. Я имею в виду, когда приходят новые данные, я хочу увидеть их в окне графика. Также я хочу, чтобы окно графика открывалось при запуске системы. После многих поисков и испытаний вторая часть кода сделала то, что я хочу, и выглядит хорошо для меня. Это можно прочитать и построить данные. Проблема в том, что я хотел бы реализовать его для моего существующего кода, который разработан объектно-ориентированным способом, но, как вы можете видеть, программа построения сюжета (вторая) работает последовательно. Я не смог добиться того, чтобы это работало в моем существующем коде. Было бы здорово, если бы вы могли помочь мне.
примечание: основной код (первый) - это упрощенная версия существующей программы.
Заранее спасибо.
Редактировать: я внес следующие изменения и получил сообщение об ошибке «У объекта GUI нет атрибута« обновление »».
импорт matplotlib.animation как анимация -> ... как анимация
в функции DataPlotter: anim = self.anim.FuncAnimation (self.fig, update) ->
anim = animation.FuncAnimation (self.fig, update)
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont
from tkinter import Menu
from tkinter import messagebox as msg
from threading import Thread
from threading import Timer
from queue import Queue
import time
from time import sleep
import serial
from shutil import copyfile
import os
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
#=====================================================
class GUI():
def __init__(self):
self.root = tk.Tk()
self.port=serial.Serial("/dev/ttyUSB0", 115200)
self.root.title("Python GUI")
self.create_widgets()
self.fig = plt.figure()
self.ax1 = self.fig.add_subplot(1,1,1)
self.line1, = self.ax1.plot([], [], lw=1, marker = '*', linestyle='-', color='r')
def start(self):
print("started")
self.create_DataReader_Thread()
self.create_DataRecord_Thread()
self.create_DataPlotter_Thread()
day = time.strftime('%d'); month = time.strftime('%m')
year = time.strftime('%y'); hour = time.strftime('%H')
minute = time.strftime('%M')
self.PC1 = open('Channel_1_'+day+month+year+'_'+hour+minute+'.txt', 'a')
def stop(self):
print("stopped")
def reset(self):
print("resetted")
def quit_(self):
self.root.quit()
self.root.destroy()
#===============================================================================
def create_DataPlotter_Thread(self):
self.run_thread = Thread(target=self.DataPlotter)
self.run_thread.setDaemon(True)
self.run_thread.start()
def DataPlotter(self):
idx=0
while True:
old_len=len(self.l1)
if idx != old_len:
idx+=1
old_len=idx
def update(i):
if len(self.l1)>1:
self.ax1.set_xlim(-5, max(x)+10)
if max(self.l1)>50:
self.ax1.set_ylim(-5, max(y)+10)
line1.set_data(range(1,len(self.l1)), self.l1)
return self.line1
anim = animation.FuncAnimation(self.fig, self.update)
plt.show()
#===============================================================================
def create_DataRecord_Thread(self):
self.run_thread = Thread(target=self.DataRecorder)
self.run_thread.setDaemon(True)
def DataRecorder(self):
idx=0
while True:
old_len=len(self.l1)
if idx != old_len:
print("new data received !")
idx+=1
old_len=idx
self.PC1.write(str(self.cnt1[0]) + '\n'), self.PC1.seek(0)
#===============================================================================
def create_DataReader_Thread(self):
self.run_thread = Thread(target=self.DataReader)
self.run_thread.setDaemon(True)
self.run_thread.start()
def DataReader(self):
self.l1=[]; self.l2=[]; self.l3=[]; self.l4=[]; self.l5=[]; self.l6=[]; self.l7=[]; self.l8=[]; self.l9=[];
j=0
while True:
ans=self.port.read(28)
j+=1
print('------------- ',j,' ------------------')
for i in range(0,9):
counter_bytes=ans[3*i+1:3*i+4]
first = bin(counter_bytes[0])[2:].zfill(8)
second = bin(counter_bytes[1])[2:].zfill(8)
third = bin(counter_bytes[2])[2:].zfill(8)
counter_bin = first + second + third
counter_dec=int(counter_bin,2)
if i==0: self.cnt1=counter_dec, self.l1.append(counter_dec)
elif i==1: self.cnt2=counter_dec, self.l2.append(counter_dec)
elif i==2: self.cnt3=counter_dec, self.l3.append(counter_dec)
elif i==3: self.cnt4=counter_dec, self.l4.append(counter_dec)
elif i==4: self.cnt5=counter_dec, self.l5.append(counter_dec)
elif i==5: self.cnt6=counter_dec, self.l6.append(counter_dec)
elif i==6: self.cnt7=counter_dec, self.l7.append(counter_dec)
elif i==7: self.cnt8=counter_dec, self.l8.append(counter_dec)
elif i==8: self.cnt9=counter_dec, self.l9.append(counter_dec)
self.c1.set(self.cnt1[0]); self.c2.set(self.cnt2[0]); self.c3.set(self.cnt3[0]); self.c4.set(self.cnt4[0]); self.c5.set(self.cnt5[0]);
self.c6.set(self.cnt6[0]); self.c7.set(self.cnt7[0]); self.c8.set(self.cnt8[0]); self.c9.set(self.cnt9[0]);
################################################################################
def create_widgets(self):
tabControl = ttk.Notebook(self.root) # Create Tab Control
tab1 = ttk.Frame(tabControl) # Create a tab
tabControl.add(tab1, text='CONTROL') # Add the tab
tabControl.pack(expand=1, fill="both") # Pack to make visible
buttons_frame=ttk.Frame(tab1, relief="raised")
buttons_frame.place(x=10, y=50, height=200, width=140)
button1 = tk.Button(tab1, text='START', fg='black', font='none 15 bold', command=self.start)
button2 = tk.Button(tab1, text='STOP' , fg='black', font='none 15 bold', command=self.stop)
button1.place(x= 80 , y= 100, anchor='c')
button2.place(x= 80 , y= 200, anchor='c')
Channels_frame=ttk.Frame(tab1, relief="raised")
Channels_frame.place(x=200, y=50, height=350, width=530)
Channel_1 = ttk.Label(Channels_frame, text = 'Channel 1 : ')
Channel_2 = ttk.Label(Channels_frame, text = 'Channel 2 : ')
Channel_3 = ttk.Label(Channels_frame, text = 'Channel 3 : ')
Channel_4 = ttk.Label(Channels_frame, text = 'Channel 4 : ')
Channel_5 = ttk.Label(Channels_frame, text = 'Channel 5 : ')
Channel_6 = ttk.Label(Channels_frame, text = 'Channel 6 : ')
Channel_7 = ttk.Label(Channels_frame, text = 'Channel 7 : ')
Channel_8 = ttk.Label(Channels_frame, text = 'Channel 8 : ')
Channel_9 = ttk.Label(Channels_frame, text = 'Channel 9 : ')
Channel_1.place(x=100, y=50 , anchor='c')
Channel_2.place(x=280, y=50 , anchor='c')
Channel_3.place(x=430, y=50 , anchor='c')
Channel_4.place(x=100, y=150, anchor='c')
Channel_5.place(x=280, y=150, anchor='c')
Channel_6.place(x=430, y=150, anchor='c')
Channel_7.place(x=100, y=250, anchor='c')
Channel_8.place(x=280, y=250, anchor='c')
Channel_9.place(x=430, y=250, anchor='c')
Channel_1.config(font='none 12 bold')
Channel_2.config(font='none 12 bold')
Channel_3.config(font='none 12 bold')
Channel_4.config(font='none 12 bold')
Channel_5.config(font='none 12 bold')
Channel_6.config(font='none 12 bold')
Channel_7.config(font='none 12 bold')
Channel_8.config(font='none 12 bold')
Channel_9.config(font='none 12 bold')
self.c1 = tk.IntVar()
self.c2 = tk.IntVar()
self.c3 = tk.IntVar()
self.c4 = tk.IntVar()
self.c5 = tk.IntVar()
self.c6 = tk.IntVar()
self.c7 = tk.IntVar()
self.c8 = tk.IntVar()
self.c9 = tk.IntVar()
count_1 = ttk.Label(Channels_frame, textvariable=self.c1)
count_2 = ttk.Label(Channels_frame, textvariable=self.c2)
count_3 = ttk.Label(Channels_frame, textvariable=self.c3)
count_4 = ttk.Label(Channels_frame, textvariable=self.c4)
count_5 = ttk.Label(Channels_frame, textvariable=self.c5)
count_6 = ttk.Label(Channels_frame, textvariable=self.c6)
count_7 = ttk.Label(Channels_frame, textvariable=self.c7)
count_8 = ttk.Label(Channels_frame, textvariable=self.c8)
count_9 = ttk.Label(Channels_frame, textvariable=self.c9)
count_1.place(x=100, y=90 , anchor='c')
count_2.place(x=280, y=90 , anchor='c')
count_3.place(x=430, y=90 , anchor='c')
count_4.place(x=100, y=190, anchor='c')
count_5.place(x=280, y=190, anchor='c')
count_6.place(x=430, y=190, anchor='c')
count_7.place(x=100, y=290, anchor='c')
count_8.place(x=280, y=290, anchor='c')
count_9.place(x=430, y=290, anchor='c')
count_1.config(font='none 14 ')
count_2.config(font='none 14 ')
count_3.config(font='none 14 ')
count_4.config(font='none 14 ')
count_5.config(font='none 14 ')
count_6.config(font='none 14 ')
count_7.config(font='none 14 ')
count_8.config(font='none 14 ')
count_9.config(font='none 14 ')
menubar = Menu(self.root)
self.root.config(menu=menubar)
exitmenu = Menu(menubar, tearoff=0)
exitmenu.add_command(label="EXIT", command = self.quit_)
menubar.add_cascade(label ="Quit", menu = exitmenu)
gui = GUI()
gui.root.geometry('750x500')
gui.root.mainloop()
=============================================== ==============
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from matplotlib import animation
import time
from time import sleep
import serial
x=[]
y=[]
port = serial.Serial('/dev/ttyUSB0', 115200)
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
line1, = ax1.plot([], [], lw=1, marker = '*', linestyle='-', color='r')
def update(i):
while True:
y.append(ord(port.read()))
x.append(i)
if len(x)>1:
ax1.set_xlim(-5, max(x)+10)
if max(y)>50:
ax1.set_ylim(-5, max(y)+10)
line1.set_data(x, y)
return line1
anim = animation.FuncAnimation(fig, update)
plt.show()