.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "gallery/user_interfaces/embedding_in_tk_sgskip.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. meta:: :keywords: codex .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_gallery_user_interfaces_embedding_in_tk_sgskip.py: =============== Embedding in Tk =============== .. GENERATED FROM PYTHON SOURCE LINES 7-67 .. code-block:: Python import tkinter import numpy as np # Implement the default Matplotlib key bindings. from matplotlib.backend_bases import key_press_handler from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk) from matplotlib.figure import Figure root = tkinter.Tk() root.wm_title("Embedding in Tk") fig = Figure(figsize=(5, 4), dpi=100) t = np.arange(0, 3, .01) ax = fig.add_subplot() line, = ax.plot(t, 2 * np.sin(2 * np.pi * t)) ax.set_xlabel("time [s]") ax.set_ylabel("f(t)") canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea. canvas.draw() # pack_toolbar=False will make it easier to use a layout manager later on. toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False) toolbar.update() canvas.mpl_connect( "key_press_event", lambda event: print(f"you pressed {event.key}")) canvas.mpl_connect("key_press_event", key_press_handler) button_quit = tkinter.Button(master=root, text="Quit", command=root.destroy) def update_frequency(new_val): # retrieve frequency f = float(new_val) # update data y = 2 * np.sin(2 * np.pi * f * t) line.set_data(t, y) # required to update canvas and attached toolbar! canvas.draw() slider_update = tkinter.Scale(root, from_=1, to=5, orient=tkinter.HORIZONTAL, command=update_frequency, label="Frequency [Hz]") # Packing order is important. Widgets are processed sequentially and if there # is no space left, because the window is too small, they are not displayed. # The canvas is rather flexible in its size, so we pack it last which makes # sure the UI controls are displayed as long as possible. button_quit.pack(side=tkinter.BOTTOM) slider_update.pack(side=tkinter.BOTTOM) toolbar.pack(side=tkinter.BOTTOM, fill=tkinter.X) canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=True) tkinter.mainloop() .. _sphx_glr_download_gallery_user_interfaces_embedding_in_tk_sgskip.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: embedding_in_tk_sgskip.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: embedding_in_tk_sgskip.py ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_