首页 > 解决方案 > 如何在 tkinter 画布中嵌入 matplotlib 图形时获得(3d)交互性工作

问题描述

我在 tkinter gui 画布中嵌入了一个 3D matplotlib 图,但无法让(鼠标)交互性(旋转/缩放等)工作。如果我只使用“pyplot.show()”命令而不嵌入 tk 交互工作,我是否必须手动设置所有回调才能与 tkinter 嵌入一起使用,还是有一种简单的方法?

显示多维数据集的简单示例脚本:

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()

标签: pythonmatplotlibtkinter3dinteractive

解决方案


必须将画布对象的交互回调重新绑定/连接到图形轴对象

canvas.mpl_connect('button_press_event', view.axes._button_press)
canvas.mpl_connect('button_release_event', view.axes._button_release)
canvas.mpl_connect('motion_notify_event', view.axes._on_move)

就像在这个例子中所做的那样:

https://github.com/precise-simulation/mesh-viewer/blob/master/meshviewer_mpl_tk.py#L296-L298


推荐阅读