Python implementation in tkinter using matplotlib to draw graphics method example, tkintermatplotlib
This example describes how to use matplotlib to draw a graph in tkinter using Python. We will share this with you for your reference. The details are as follows:
I. Code:
# Coding = utf-8import sysimport Tkinter as Tkimport matplotlibfrom numpy import arange, sin, pifrom matplotlib. backends. backend_tk1_import figurecanvastk.pdf, NavigationToolbar2TkAggfrom matplotlib. backend_bases import key_press_handlerfrom matplotlib. figure import Figurematplotlib. use ('tkting') root = Tk. tk () root. title ("--matplotlib in TK") # Set the image size and quality f = Figure (figsize = (5, 4), dpi = 100) a = f. add_subplot (111) t = arange (0.0, 3, 0.01) s = sin (2 * pi * t) # plot. plot (t, s) # display the drawn image to the tkinter window canvas = figurecanvastk.pdf (f, master = root) canvas. show () canvas. get_tk_widget (). pack (side = Tk. TOP, fill = Tk. BOTH, expand = 1) # display the navigation toolbar of matplotlib to the tkinter window toolbar = navigationtoolbar2tk.pdf (canvas, root) toolbar. update () canvas. _ tkcanvas. pack (side = Tk. TOP, fill = Tk. BOTH, expand = 1) # define and bind the keyboard event handler function 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) # click the event processing function def _ quit (): # end the main event loop and destroy the application window root. quit () root. destroy () button = Tk. button (master = root, text = 'quit', command = _ Quit) button. pack (side = Tk. BOTTOM) Tk. mainloop ()
Ii. Running result: