Python圖形編程探索系列-09-tkinter與matplotlib結合案例

案例1

案例來自於:https://bbs.csdn.net/topics/390326088
代碼示例:html

import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from 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, y

def 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。 canvas


代碼示例1:app

import tkinter as tk
import matplotlib
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure

# matplotlib.use('TkAgg')

root = tk.Tk()
root.title("matplotlib in tkinter")

# set a figure
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)


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()

運行結果:dom


 

 

代碼實例2 ide


https://stackoverflow.com/questions/35829961/using-matplotlib-with-tkinter-tkagg函數

import matplotlib
matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
# Implement the default mpl key bindings
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

root = 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.DrawingArea
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()
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 tstate

button = Tk.Button(master=root, text='Quit', command=_quit)
button.pack(side=Tk.BOTTOM)
Tk.mainloop()

案例3

參考 http://www.cnblogs.com/chaosimple/p/4029687.htmloop

import numpy as np
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

def 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()

運行結果:
佈局

 

代碼第二版本 ui


參考:http://www.javashuo.com/article/p-rjfmqyoh-hu.html
有些場合,咱們須要對數據可視化。單是靠 tkinter 難度太大,並且作出來的效果不必定理想。此時,將 tkinter 與 matplotlib 結合,是最好的選擇。知識點:將 tkinter 與 matplotlib 結合的整個套路是固定的,只須要關心咱們的繪圖邏輯和程序邏輯便可。

import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import tkinter as tk
class 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()

結果:


相關文章
相關標籤/搜索