I am trying to embed a matplotlib window inside a tkinter GUI, but I am having trouble getting the "slider" widget to show up. In fact, the code below does show an embedded image, but the image itself is behaving like a slider, if you click on it!
I have tried using the ideas from this question
Placing plot on Tkinter main window in Python
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib.widgets import Slider
import Tkinter as tk
class Embed:
def __init__(self, root):
self.root = root
self.plot = Plotting(self.root)
self.a = np.array([[1,2,3],[2,3,4],[3,4,5]])
self.b = np.array([[1,2,3],[4,5,6],[7,8,9]])
self.ctuple = (self.a,self.b)
self.cube = np.dstack(self.ctuple)
self.button = tk.Button(root, text="check", command=lambda: self.plot.plot(self.cube))
self.button.pack()
class Plotting:
def __init__(self, root):
self.root = root
def plot(self, cube, axis=2, **kwargs):
fig = Figure(figsize=(6,6))
ax = fig.add_subplot(111)
s = [slice(0,1) if i == axis else slice(None) for i in xrange(3)]
im = cube[s].squeeze()
l = ax.imshow(im, **kwargs)
canvas = FigureCanvasTkAgg(fig, self.root)
canvas.get_tk_widget().pack()
canvas.draw()
slider = Slider(ax, 'Axis %i index' % axis, 0, cube.shape[axis] - 1,
valinit=0, valfmt='%i')
def update(val):
ind = int(slider.val)
s = [slice(ind, ind + 1) if i == axis else slice(None)
for i in xrange(3)]
im = cube[s].squeeze()
l.set_data(im, **kwargs)
canvas.draw()
slider.on_changed(update)
if __name__ == '__main__':
root = tk.Tk()
app = Embed(root)
root.mainloop()
root.destroy()
any help is much appreciated!