我已在 tkinter gui Canvas 中嵌入了 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()
最佳答案
必须重新绑定(bind)/连接从 Canvas 对象到图形轴对象的交互回调
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
关于python - 如何在 tkinter Canvas 中嵌入 matplotlib 图形时获得 (3d) 交互性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62809702/