Skip to content

Instantly share code, notes, and snippets.

@ianhi
Created September 2, 2020 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianhi/3bf2151cff1a56ed1ac779203424d99c to your computer and use it in GitHub Desktop.
Save ianhi/3bf2151cff1a56ed1ac779203424d99c to your computer and use it in GitHub Desktop.
test of embedding matplotlib in tkinter with interactivity
"""
based on https://matplotlib.org/3.1.0/gallery/user_interfaces/embedding_in_tk_sgskip.html
"""
import tkinter
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
from mpl_interactions import *
# import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(211)
t = np.arange(0, 3, .01)
# fig, ax = plt.subplots()
t = np.arange(0.0, 1.0, 0.001)
l = ax.plot(t, np.sin(2 * np.pi * t))[0]
# plt.subplots_adjust(left=0.25, bottom=0.25)
axfreq = fig.add_subplot(212) # define like this incase pyplot is messing things up
# axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=1)
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def update(val):
freq = sfreq.val
l.set_ydata(np.sin(2*np.pi*freq*t))
fig.canvas.draw_idle()
# neither of the below worked for me
# fig.canvas.draw()
# canvas.draw()
sfreq.on_changed(update)
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect("key_press_event", on_key_press)
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
tkinter.mainloop()
# If you put root.destroy() here, it will cause an error if the window is
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment