{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Embed in Tk\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import tkinter\n\nimport numpy as np\n\n# Implement the default Matplotlib key bindings.\nfrom matplotlib.backend_bases import key_press_handler\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\nfrom matplotlib.figure import Figure\n\nroot = tkinter.Tk()\nroot.wm_title(\"Embedded in Tk\")\n\nfig = Figure(figsize=(5, 4), dpi=100)\nt = np.arange(0, 3, .01)\nax = fig.add_subplot()\nline, = ax.plot(t, 2 * np.sin(2 * np.pi * t))\nax.set_xlabel(\"time [s]\")\nax.set_ylabel(\"f(t)\")\n\ncanvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.\ncanvas.draw()\n\n# pack_toolbar=False will make it easier to use a layout manager later on.\ntoolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)\ntoolbar.update()\n\ncanvas.mpl_connect(\n    \"key_press_event\", lambda event: print(f\"you pressed {event.key}\"))\ncanvas.mpl_connect(\"key_press_event\", key_press_handler)\n\nbutton_quit = tkinter.Button(master=root, text=\"Quit\", command=root.destroy)\n\n\ndef update_frequency(new_val):\n    # retrieve frequency\n    f = float(new_val)\n\n    # update data\n    y = 2 * np.sin(2 * np.pi * f * t)\n    line.set_data(t, y)\n\n    # required to update canvas and attached toolbar!\n    canvas.draw()\n\n\nslider_update = tkinter.Scale(root, from_=1, to=5, orient=tkinter.HORIZONTAL,\n                              command=update_frequency, label=\"Frequency [Hz]\")\n\n# Packing order is important. Widgets are processed sequentially and if there\n# is no space left, because the window is too small, they are not displayed.\n# The canvas is rather flexible in its size, so we pack it last which makes\n# sure the UI controls are displayed as long as possible.\nbutton_quit.pack(side=tkinter.BOTTOM)\nslider_update.pack(side=tkinter.BOTTOM)\ntoolbar.pack(side=tkinter.BOTTOM, fill=tkinter.X)\ncanvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=True)\n\ntkinter.mainloop()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}