|
楼主 |
发表于 2020-9-1 14:53:34
|
显示全部楼层
import tkinter
#-------------设置
import matplotlib
matplotlib.use('Agg') #该模式下绘图无法显示,plt.show()也无法作用
#-------------
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
'''
import matplotlib.pyplot as plt
import numpy as np
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
# 1. 用matplotlib.figure->Figure画图---------------------------------------
#fig = Figure(figsize=(5, 4), dpi=100)
#fig_plot = fig.add_subplot(111)
#t = np.arange(0, 3, .01)
#fig_plot.plot(t, 2 * np.sin(2 * np.pi * t))
#----------------------------------------------------------------------
# 2. 用pyplot.subplots画图-------------------------------------------------
#fig, axs = plt.subplots(1, 3, figsize=(5, 4), sharey=True)
#data = {'apples': 10, 'oranges': 15, 'lemons': 5, 'limes': 20}
#names = list(data.keys())
#values = list(data.values())
#axs[0].bar(names, values)
#axs[1].scatter(names, values)
#axs[2].plot(names, values)
#fig.suptitle('Categorical Plotting')
#--------------------------------------------------------------------
# 3. 用pyplot.figure画图-------------------------------------------------
fig = plt.figure(figsize=(5, 4), tight_layout=True)
ax = fig.add_subplot(111)
ax.plot(np.arange(0, 1e6, 1000))
ax.set_ylabel('YLabel0')
ax.set_xlabel('XLabel0')
for tick in ax.get_xticklabels():
tick.set_rotation(90)
#fig.align_labels() # same as fig.align_xlabels(); fig.align_ylabels()
#------------------------------------
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
#matplotlib工具条---------------------------------
#toolbar = NavigationToolbar2Tk(canvas, root)
#toolbar.update()
#canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect("key_press_event", on_key_press)
def _quit():
print('quit')
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
tkinter.mainloop()
# If you put root.destroy() here, it will cause an error if the window is
# closed with the window manager
'''
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import openpyxl as xl
import matplotlib.pyplot as plt
from tkinter import filedialog
root = tkinter.Tk() # 创建tkinter的主窗口
root.title("在tkinter中使用matplotlib")
f = plt.figure(figsize=(5, 4), tight_layout=True)
#ax = f.add_subplot(111)
'''
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111) # 添加子图:1行1列第1个
# 生成用于绘sin图的数据
x = np.arange(0, 3, 0.01)
y = np.sin(2 * np.pi * x)
# 在前面得到的子图上绘图
a.plot(x, y)
'''
def _start():
def get_data(path):
wb = xl.load_workbook(path,data_only=True)
ws = wb.active
hezha_lst = []
A_lst = []
B_lst = []
C_lst = []
for row in ws.iter_rows(min_row=2,max_row=4,min_col=1,max_col=4):
# print(row[0].value,row[4].value)
hezha_lst.append(row[0].value)
A_lst.append(row[1].value)
B_lst.append(row[2].value)
C_lst.append(row[3].value)
return hezha_lst,A_lst,B_lst,C_lst
def chart(x,y1,y2,y3):
plt.plot(x,y1,label='A相')
plt.scatter(x,y1,color='r')
plt.plot(x,y2,label='B相')
plt.scatter(x,y2,color='g')
plt.plot(x,y3,label='C相')
plt.scatter(x,y3,color='b')
plt.title('合闸数据分析')
#plt.legend()
#plt.savefig('test.png')
#plt.show()
path = filedialog.askopenfilename(title='选择Excel文件路径', filetypes=[('*.xlsx', '.xlsx')])
plt.rcParams['font.sans-serif']=['SIMHEI'] #防止中文乱码
get_data(path)
chart(*get_data(path))
# 将绘制的图形显示到tkinter:创建属于root的canvas画布,并将图f置于画布上
canvas = FigureCanvasTkAgg(f, master=root)
canvas.draw() # 注意show方法已经过时了,这里改用draw
canvas.get_tk_widget().place(height=300,width=300,x=150, y=20)
# matplotlib的导航工具栏显示上来(默认是不会显示它的)
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas._tkcanvas.place(height=300,width=300)
'''
def on_key_event(event):
"""键盘事件处理"""
print("你按了%s" % event.key)
key_press_handler(event, canvas, toolbar)
# 绑定上面定义的键盘事件处理函数
canvas.mpl_connect('key_press_event', on_key_event)
'''
def _quit():
"""点击退出按钮时调用这个函数"""
root.quit() # 结束主循环
root.destroy() # 销毁窗口
def qingchu():
plt.close('all')
root.geometry('595x560') # 设置窗口大小
root.resizable(width=False, height=False) # 禁止拉伸根窗口
'''
scrollbar = Scrollbar(root) # 设置滚动条
text = Text(root,font=('宋体', 15),height=18, width=57, bg='#cbeaf8', undo=True,yscrollcommand=scrollbar.set)
text.grid(columnspan=3)
scrollbar.config(command=text.yview)
scrollbar.grid(row=0, column=3, stick=E + N + S)
'''
# 创建一个按钮,并把上面那个函数绑定过来
button_1 = tkinter.Button(master=root, text="退出", command=_quit,width=11)
# 按钮放在下边
button_1.place(x=300, y=373)
# 创建一个按钮,并把上面那个函数绑定过来
button_2 = tkinter.Button(master=root, text="启动", command=_start,width=11)
# 按钮放在下边
button_2.place(x=460, y=373)
button_3 = tkinter.Button(master=root, text="清除画布", command=qingchu)
# 按钮放在下边
button_3.place(x=150, y=373)
# 主循环
mainloop()
这是我测试这个的代码 |
|