案例1
案例来自于:
代码示例:import matplotlibmatplotlib.use('TkAgg')from matplotlib.backends.backend_tkagg import FigureCanvasTkAggfrom matplotlib.figure import Figurefrom tkinter import *root = Tk()root.title("tkinter and matplotlib")f = Figure(figsize=(5, 4), dpi=100)f_plot = f.add_subplot(111)def other_picture_alg(): #数据相关的算法应该与plot分离开 x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y = [3, 6, 9, 12, 15, 18, 15, 12, 15, 18] return x, ydef draw_picture(): f_plot.clear() x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #关于数据的部分可以提取出来 y = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] f_plot.plot(x, y) canvs.draw()def draw_picture2(): f_plot.clear() x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #关于数据的部分可以提取出来 y = [2, 4, 6, 8, 10, 8, 6, 4, 2, 0] f_plot.plot(x, y) canvs.draw()def draw_picture3(): f_plot.clear() x, y = other_picture_alg() # 使用由算法生成的数据,可以避免重复的运算过程 f_plot.plot(x, y) canvs.draw()canvs = FigureCanvasTkAgg(f, root)canvs.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)Button(root, text='pic', command=draw_picture).pack()Button(root, text='pic2', command=draw_picture2).pack()Button(root, text='pic3', command=draw_picture3).pack()root.mainloop()
运行结果:
案例2
这个案例网上流传的比较多,这里只是一个参考例子,原始版本看代码示例2。
代码示例1:import tkinter as tkimport matplotlibfrom numpy import arange, sin, pifrom matplotlib.backends.backend_tkagg import FigureCanvasTkAggfrom matplotlib.backends.backend_tkagg import NavigationToolbar2TkAggfrom matplotlib.backend_bases import key_press_handlerfrom matplotlib.figure import Figure# matplotlib.use('TkAgg')root = tk.Tk()root.title("matplotlib in tkinter")# set a figuref = Figure(figsize=(5, 4), dpi=100)a = f.add_subplot(111)t = arange(0.0, 3.0, 0.01)s = sin(2*pi*t)a.plot(t, s)canvas = FigureCanvasTkAgg(f, master=root)canvas.show()canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)toolbar = NavigationToolbar2TkAgg(canvas, root)toolbar.update()def on_key_event(event): print('you press %s' %event.key) key_press_handler(event, canvas, toolbar)canvas.mpl_connect('key_press_event', on_key_event)def _quit(): root.quit() root.destroy()button = tk.Button(root, text='quit', command=_quit)button.pack(side=tk.BOTTOM)root.mainloop()
运行结果:
代码实例2
import matplotlibmatplotlib.use('TkAgg')from numpy import arange, sin, pifrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg# Implement the default mpl key bindingsfrom matplotlib.backend_bases import key_press_handlerfrom matplotlib.figure import Figureimport sysif sys.version_info[0] < 3: import Tkinter as Tkelse: import tkinter as Tkroot = Tk.Tk()root.wm_title("Embedding in TK")f = Figure(figsize=(5, 4), dpi=100)a = f.add_subplot(111)t = arange(0.0, 3.0, 0.01)s = sin(2*pi*t)a.plot(t, s)# A tk.DrawingAreacanvas = FigureCanvasTkAgg(f, master=root)canvas.show()canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)toolbar = NavigationToolbar2TkAgg(canvas, root)toolbar.update()canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)def on_key_event(event): print('you pressed %s' % event.key) key_press_handler(event, canvas, toolbar)canvas.mpl_connect('key_press_event', on_key_event)def _quit(): root.quit() # Stops mainloop root.destroy() # This is necessary on Windows to prevent # Fatal Python Error: PyEval_RestoreThread: NULL tstatebutton = Tk.Button(master=root, text='Quit', command=_quit)button.pack(side=Tk.BOTTOM)Tk.mainloop()
案例3
参考
import numpy as npfrom tkinter import *from matplotlib.backends.backend_tkagg import FigureCanvasTkAggfrom matplotlib.figure import Figuredef drawPic(): try: sampleCount=int(inputEntry.get()) except: sampleCount=50 print('请输入整数') nputEntry.delete(0, END) inputEntry.insert(0, '50') #清空图像,以使得前后两次绘制的图像不会重叠 drawPic.f.clf() drawPic.a = drawPic.f.add_subplot(111) #在[0,100]范围内随机生成sampleCount个数据点 x = np.random.randint(0, 100, size=sampleCount) y = np.random.randint(0, 100, size=sampleCount) color = ['b', 'r', 'y', 'g'] #绘制这些随机点的散点图,颜色随机选取 drawPic.a.scatter(x, y, s=3, color=color[np.random.randint(len(color))]) drawPic.a.set_title('Demo: Draw N Random Dot') drawPic.canvas.show()if __name__ == '__main__': root = Tk() #在Tk的GUI上放置一个画布,并用.grid()来调整布局 drawPic.f = Figure(figsize=(5, 4), dpi=100) drawPic.canvas = FigureCanvasTkAgg(drawPic.f, master=root) drawPic.canvas.show() drawPic.canvas.get_tk_widget().grid(row=0, columnspan=3) #放置标签、文本框和按钮等部件,并设置文本框的默认值和按钮的事件函数 Label(root, text='请输入样本数量:').grid(row=1, column=0) inputEntry = Entry(root) inputEntry.grid(row=1, column=1) inputEntry.insert(0, '50') Button(root, text='画图', command=drawPic).grid(row=1, column=2, columnspan=3) #启动事件循环 root.mainloop()
运行结果:
代码第二版本
参考: 有些场合,我们需要对数据可视化。单是靠 tkinter 难度太大,而且做出来的效果不一定理想。此时,将 tkinter 与 matplotlib 结合,是最好的选择。知识点:将 tkinter 与 matplotlib 结合的整个套路是固定的,只需要关心我们的绘图逻辑和程序逻辑即可。import matplotlibmatplotlib.use('TkAgg')import numpy as npfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAggfrom matplotlib.figure import Figureimport tkinter as tkclass Application(tk.Tk): ''' 文件夹选择程序 界面与逻辑分离 ''' def __init__(self): '''初始化''' super().__init__() # 有点相当于tk.Tk() self.wm_title("Embed matplotlib in tkinter") self.createWidgets() def createWidgets(self): '''界面''' fig = Figure(figsize=(5, 4), dpi=100) self.ax = fig.add_subplot(111) self.canvas = FigureCanvasTkAgg(fig, master=self) self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(self.canvas, self) toolbar.update() footframe = tk.Frame(master=self).pack(side=tk.BOTTOM) tk.Button(master=footframe, text='重画', command=self.draw).pack(side=tk.BOTTOM) tk.Button(master=footframe, text='退出', command=self._quit).pack(side=tk.BOTTOM) self.draw() # 绘图 def draw(self): '''绘图逻辑''' x = np.random.randint(0, 50, size=100) y = np.random.randint(0, 50, size=100) # self.fig.clf() # 方式一:①清除整个Figure区域 # self.ax = self.fig.add_subplot(111) # ②重新分配Axes区域 self.ax.clear() # 方式二:①清除原来的Axes区域 self.ax.scatter(x, y, s=3) # 重新画 self.canvas.show() def _quit(self): '''退出''' self.quit() # 停止 mainloop self.destroy() # 销毁所有部件if __name__ == '__main__': # 实例化Application app = Application() # 主消息循环: app.mainloop()
结果: