tkinter的GUI設計:界面與邏輯分離(四)-- 與 matplotlib 結合

有些場合,咱們須要對數據可視化。單是靠 tkinter 難度太大,並且作出來的效果不必定理想。canvas

此時,將 tkinter 與 matplotlib 結合,是最好的選擇。app

知識點:dom

將 tkinter 與 matplotlib 結合的整個套路是固定的,只須要關心咱們的繪圖邏輯程序邏輯便可ide

 

 

import matplotlib
matplotlib.use('TkAgg')

import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, 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()
相關文章
相關標籤/搜索