How to get (3d) interactivity to work while embedding a matplotlib figure in a tkinter canvas

Viewed 779

I have embedded a 3D matplotlib plot in a tkinter gui canvas, but can't get the (mouse) interactivity (rotate/zoom etc) to work. If I just use the "pyplot.show()" command without embedding in tk the interactivity works, do I have to manually set all callbacks for this to work with tkinter embedding or is there a simple way?

Simple example script displaying a cube:

import tkinter as tk
from tkinter.ttk import *

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib import pyplot
from mpl_toolkits import mplot3d

import numpy
from stl import mesh


tk_root = tk.Tk()

figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)

data = numpy.zeros(6, dtype=mesh.Mesh.dtype)
data['vectors'][0] = numpy.array([[0, 1, 1],[1, 0, 1],[0, 0, 1]])
data['vectors'][1] = numpy.array([[1, 0, 1],[0, 1, 1],[1, 1, 1]])
data['vectors'][2] = numpy.array([[1, 0, 0],[1, 0, 1],[1, 1, 0]])
data['vectors'][3] = numpy.array([[1, 1, 1],[1, 0, 1],[1, 1, 0]])
data['vectors'][4] = numpy.array([[0, 0, 0],[1, 0, 0],[1, 0, 1]])
data['vectors'][5] = numpy.array([[0, 0, 0],[0, 0, 1],[1, 0, 1]])
msh = mesh.Mesh(data)

axes.add_collection3d(mplot3d.art3d.Poly3DCollection(msh.vectors))
# pyplot.show()

canvas = FigureCanvasTkAgg(figure, tk_root)
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2Tk(canvas, tk_root)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

tk_root.mainloop()
2 Answers

The accepted answer is a valid solution to your question, but I would recommend against using pyplot with tkinter as it can lead to all sorts of problems that I myself don't understand (ex: closing the tkinter window will leave pyplot running). Instead I would do something like this:

import tkinter as tk
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure


data=np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
X=np.array([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
Y=np.array([[2, 2, 2], [1, 1, 1], [0, 0, 0]])
tk_root = tk.Tk()

figure = Figure(figsize=(12, 8))
ax= figure.add_subplot(1, 1, 1, projection='3d')
ax.plot_surface(data, X, Y, shade=True)
canvas = FigureCanvasTkAgg(figure, tk_root)
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
canvas.mpl_connect('button_press_event', ax._button_press)
canvas.mpl_connect('button_release_event', ax._button_release)
canvas.mpl_connect('motion_notify_event', ax._on_move)

tk_root.mainloop()

I understand this answer doesn't perfectly fit the context of you question, but this is the general idea

Related