定制界面读取 txt 文件并且绘图(python)
摘要:本文主要使用tkinter定制GUI,读取txt文件,使用matplotlib绘图。
00 导入所需库
import os
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['font.serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
import matplotlib.pyplot as plt
from tkinter import *
from tkinter import filedialog
###
01 定制GUI
def readtxt():
global ftype
ftype=filedialog.askopenfilename(title='打开 *.txt',filetypes=[('LE-100','*.txt')])
win=Tk()
win.title('技术邻')
b1=Button(win,text='txt数据',relief='raised',font='宋体 20 bold',width=15,command=readtxt)
b1.pack(padx=50,pady=10,side='left')
b2=Button(win,text='分析',relief='raised',font='宋体 20 bold',width=15,
foreground='purple',background='lightgray',command=win.destroy)
b2.pack(padx=50,pady=20,side='left')
win.mainloop()
###
02 读取txt文件
f_name=ftype.split('/')
f_dir='/'.join(f_name[0:-1])
os.chdir(f_dir)
fgs=f_name[-1].split('.')
if fgs[-1]=='txt':
with open(ftype,'r') as f:
vib=f.read()
vib_list=vib.split()
vib_z=vib_list[3::3]
vib_z=[int(x) for x in vib_z]
vib_y=vib_list[4::3]
vib_y=[int(x) for x in vib_y]
vib_x=vib_list[5::3]
vib_x=[int(x) for x in vib_x]
fs=250
xt=np.linspace(1/fs,len(vib_z)/fs,len(vib_z))
xt=xt.tolist()
xt=[format(x,'.3f') for x in xt]
xt=[float(x) for x in xt]
03 绘图
fig,ax=plt.subplots(3,1,sharex='all')
fig.set_size_inches(11.69,8.27)
fig.set_dpi(200)
fig.subplots_adjust(hspace=0)
ax1=ax[0]
ax1.plot(xt,vib_x)
ax1.set_ylabel('X方向振动')
ax1.set_title('LE-100测试数据')
ax1.grid(axis='both')
ax2=ax[1]
ax2.plot(xt,vib_y,linewidth=0.5)
ax2.set_ylabel('Y方向振动')
ax2.grid(axis='both')
ax3=ax[2]
ax3.plot(xt,vib_z,color='blue')
ax3.set_ylabel('Z方向振动')
ax3.set_xlabel('时间')
ax3.grid(axis='both')
fig.savefig(f_name[-1]+'.jpg')
fig.show()