2017-07-06 56 views
1

我有一个GUI,用户可以在其中加载日志文件,并可以查看框架中的日志文件,并突出显示文件中的警告和错误。基于来自tkinter中文件的输入创建图形

我也试图通过创建一个包含用户选择的日志文件中的ID和时间戳的图来可视化该文件的数据。我已经能够分别使用matplotlib创建图形,并使用plt.show()显示图形。

但是我无法将它嵌入到我的tkinter GUI中。我尝试了很多东西,但只能得到坐标轴而不是实际的棒图。当用户选择要加载的文件时,会出现日志文件等,但在画布区域中,只有轴显示并且没有绘图。

这里是我的代码部分:

import matplotlib 

matplotlib.use('TkAgg') 

from matplotlib.backends.backend_tkagg import \ 
    FigureCanvasTkAgg,NavigationToolbar2TkAgg 

from matplotlib.figure import Figure 

import matplotlib.pyplot as plt 

from tkinter import * 

from tkinter import ttk 

from tkinter.filedialog import askopenfilename 

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

root= 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=Text(frame1,width=45, height=15,bg='lightgray') 

text_static.pack(side=LEFT,fill=BOTH) 

def loadfile(): 

    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(line [-1]) 
        timeStamp.append(line[3].replace(":", "")) 


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

file=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=NavigationToolbar2TkAgg(canvas,frame1) 

toolbar.update() 

canvas._tkcanvas.pack() 

root.mainloop() 

see the result here

回答

0

的图形绘制几乎工程!但不是通过加载文件。问题是你没有使用新的数据集来更新画布,而且你也不会将它们转换为数字(浮点型?整数?)

您有时达到了设计此工具的函数式方法的限制,因为你需要参考frame_idcanvas里面的函数。 1或2班可以更容易地解决这个问题。

作为速战速决,我建议这样的功能:

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() 
相关问题