On some occasions, we need to visualize data. It is difficult to rely on tkinter alone, and the effect is not necessarily ideal.
At this point, combining Tkinter with Matplotlib is the best choice.
Knowledge Points:
The whole routine of combining tkinter with matplotlib is fixed, just care about our drawing logic and program logic
ImportMatplotlibmatplotlib.use ('Tkagg')ImportNumPy as NP fromMatplotlib.backends.backend_tkaggImportFigurecanvastkagg, Navigationtoolbar2tkagg fromMatplotlib.figureImport FigureImportTkinter as TKclassapplication (tk. TK):" "folder selector interface and logical separation" " def __init__(self):" "Initialize" "super ().__init__()#a bit equivalent to TK. Tk ()Self.wm_title ("Embed matplotlib in Tkinter") self.createwidgets ()defcreatewidgets (self):" "Interface" "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='re-painting', Command=self.draw). Pack (side=tk. BOTTOM) Tk. Button (Master=footframe, text='Exit', Command=self._quit). Pack (side=tk. BOTTOM) Self.draw ()#Drawing defDraw (self):" "Drawing Logic" "x= Np.random.randint (0,50,size=100) y= Np.random.randint (0,50,size=100) #SELF.FIG.CLF () # Method One: ① clear the entire figure area #self.ax = Self.fig.add_subplot (111) #② reallocate axes areaSelf.ax.clear ()#mode two: ① clear the original axes area
Self.ax.scatter (x, y, s=3)#re-drawself.canvas.show ()def_quit (self):" "Exit" "self.quit ()#Stop MainloopSelf.destroy ()#Destroy all parts if __name__=='__main__': #Instantiate applicationApp =application ()#main message loop:App.mainloop ()
GUI design of Tkinter: interface and logic separation (IV.)--combined with matplotlib