понимание декодирования текстового файла - PullRequest
0 голосов
/ 25 июня 2019

Я довольно новичок в python и Tkinter, и я не могу придумать, что происходит с данными файла в предложенном вами примере для решения проблемы. Может ли кто-нибудь поговорить со мной? Я планировал использовать его в программном обеспечении для CeleRacing, проекта, над которым я работал в течение года.

Я работаю в Spyder 3.7, с python 3 и matplotlib. Я пробовал альтернативы, но ни один не ударил по гвоздю так, как я хотел. Цель состоит в том, чтобы ввести текстовый документ, структурированный как:

0,3.15
1,6.43
2,5.97
3,4.88
etc.

и нанесите его на график, который обновляется каждые 1/10 секунды, так как документ заполнится преобразованными данными скорости автомобиля.

import matplotlib

matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk )

from matplotlib.figure import Figure

import matplotlib.pyplot as plt

import tkinter as tk

from tkinter import ttk

from tkinter.filedialog import askopenfilename

link,warn_list,frame_id, timeStamp=[[] for _ in range(4)]

root= tk.Tk()

Title=root.title("Tool")

label=ttk.Label(root, text="Welcome",foreground='purple',font=("Times 20 bold italic"))

label.pack()

frame1=ttk.LabelFrame(root,labelanchor='nw',height=500,width=500,text='Static Information')

frame1.pack(fill="both",expand=True)

text_static=tk.Text(frame1,width=45, height=15,bg='lightgray')

text_static.pack(side='left',fill='both')

def loadfile():
    global frame_id   # reach outside scope to use frame_id
    frame_id = []
    filename=askopenfilename(parent=root,
                             filetypes=(("Text File","*.txt"),  
                                        ("All Files","*.*")),
                             title='Choose a file')
    with open(filename, 'r')as log:
        for num,line in enumerate(log,1):
            if line.find("cam_req_mgr_process_sof")!=-1:
                    line=line.split()
                    frame_id.append(float(line [-1])) # cast to float
                    timeStamp.append(line[3].replace(":", ""))
    newplot = graph()
    newplot.canvas = canvas
    canvas.figure = newplot
    canvas.draw()


menu=tk.Menu(root)
root.config(menu=menu)

file=tk.Menu(menu)

file.add_command(label='Load', command=loadfile)

file.add_command(label='Exit',command=root.destroy)

menu.add_cascade(label='Select an option:', menu=file)

def graph():

    fig=plt.Figure()            
    x=frame_id #can use x=range(1,38) 
    y=[1]*len(x)

    ax=fig.add_subplot(111)
    ax.bar(x,y,width=0.5, color='lightgreen')
    return fig

plot=graph()

canvas=FigureCanvasTkAgg(plot,frame1)

canvas.get_tk_widget().pack()

toolbar=NavigationToolbar2Tk(canvas,frame1)

toolbar.update()

canvas._tkcanvas.pack()

root.mainloop()

и

def loadfile():
    global frame_id   # reach outside scope to use frame_id
    frame_id = []
    filename=askopenfilename(parent=root,
                             filetypes=(("Text File","*.txt"),  
                                        ("All Files","*.*")),
                             title='Choose a file')
    with open(filename, 'r')as log:
        for num,line in enumerate(log,1):
            if line.find("cam_req_mgr_process_sof")!=-1:
                    line=line.split()
                    frame_id.append(float(line [-1])) # cast to float
                    timeStamp.append(line[3].replace(":", ""))
    newplot = graph()
    newplot.canvas = canvas
    canvas.figure = newplot
    canvas.draw()

Повторяющаяся часть - это то, что я не могу собрать вместе, так как этот код не мой, и сделан PRMoureu и cbhush.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...