python - 如何在 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()
解决方案
必须将画布对象的交互回调重新绑定/连接到图形轴对象
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
推荐阅读
- webview - 我可以将 JavaScript 和 CSS 注入 Xamarin 表单 WebView 吗?
- git - 我可以强制 git 将更改视为一个整体吗?
- typescript - 如何使用 e2e 的量角器访问 div 内的滚动条
- spring-cloud-stream - 使用属性启用/禁用 Spring Cloud Stream 中的 kafka 绑定
- java - 无法上传到安卓市场
- out-of-memory - 春季作业执行上下文中的 OutOfMemoryException
- python - 在 Python 列表上使用 nn.ModuleList 会显着减慢训练速度
- javascript - 打开列表项作为新的覆盖
- c++ - 输出到文件时 endl 或 \n 不起作用。
- algorithm - 生成括号问题的问题