在tkinter绘制matplotlib图像步骤如下:
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
from math import *
gWin = None
def showPlot():
gWin.ax.clear() # gWin.fig.clear()
xs = np.linspace(-3, 3, 100)
y = [eval(gWin.fstr.get()) for x in xs]
gWin.ax.plot(xs, y, color='red', linewidth=1.0, linestyle='--')
# 5) 子图ax上画完图后,还要cavans.draw()才能刷新显示
gWin.canvas.draw()
if __name__ == '__main__':
# global gWin
gWin = tk.Tk()
frm = tk.Frame(gWin)
frm.grid(row=0, column=0, sticky="EW")
tk.Label(frm, text="y =").grid(row=0, column=0, padx=5, pady=5)
gWin.fstr = tk.StringVar()
gWin.fstr.set("sin(x)")
tk.Entry(frm, textvariable=gWin.fstr).grid(row=0, column=1, padx=5, pady=5)
tk.Button(frm, text="显示函数图", command=showPlot).grid(row=0, column=2, padx=5, pady=5)
gWin.frmPlot = tk.Frame(gWin)
# 1) 创建一个matplotlib.pyplot.Figure对象fig
gWin.fig = plt.Figure(figsize=(5, 4), dpi=100)
# 2) 在fig对象上用add_subplot()创建一个子图ax
gWin.ax = gWin.fig.add_subplot(111)
# 3) canvas = FigureCanvasTkAgg(fig, master=win)
# 得到一个将fig绑定在win上面的FigureCanvasTkAgg对象canvas
# win可以是窗口,也可以是Frame,LabelFrame
gWin.canvas = FigureCanvasTkAgg(gWin.fig, master=gWin.frmPlot)
# 4) canvas.get_tk_widget().grid(....)将canvas布局到win的合适位置
gWin.canvas.get_tk_widget().grid(row=0, column=0, sticky="ESNW")
gWin.frmPlot.grid(row=1, column=0, sticky="ESWN")
gWin.mainloop()