为什么当我在tkinter窗口中绘制三维图形时,它不允许我旋转图形或缩放



如何在tkinter图形内交互式旋转或缩放图形?它生成了一个3D绘图,但之后它保持静止,我无法与它交互并旋转/更改视点的角度。如果我在tk窗口外绘制它,它工作得很好,似乎是在尝试在界面内绘制图形时出现的错误。

绘图的功能是matplotlib文档中的洛伦兹吸引子

(python 3.7.7版(

如果需要更多细节,请不要问我。谢谢

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.animation as animation
import tkinter.messagebox
from tkinter import *
import tkinter as tk

#lorenz
def button_add():
def lorenz(x, y, z, s=10, r=5, b=28):
'''
Given:
x, y, z: a point of interest in three dimensional space
s, r, b: parameters defining the lorenz attractor
Returns:
x_dot, y_dot, z_dot: values of the lorenz attractor's partial
derivatives at the point x, y, z
'''
x_dot = s*(y - x)
y_dot = r*x - y - x*z
z_dot = x*y - b*z
return x_dot, y_dot, z_dot
dt = 0.01
num_steps = 10000 
# Need one more for the initial values
xs = np.empty(num_steps + 1)
ys = np.empty(num_steps + 1)
zs = np.empty(num_steps + 1)
# Set initial values
xs[0], ys[0], zs[0] = (0., 1., 1.05)
# Step through "time", calculating the partial derivatives at the current point
# and using them to estimate the next point
for i in range(num_steps):
x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i])
xs[i + 1] = xs[i] + (x_dot * dt)
ys[i + 1] = ys[i] + (y_dot * dt)
zs[i + 1] = zs[i] + (z_dot * dt)
# Plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(xs, ys, zs, lw=0.5)
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("Lorenz Attractor")

canvas = FigureCanvasTkAgg(fig,w)

canvas.draw()
toolbar = NavigationToolbar2Tk(canvas, w)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)   
##   plt.show()
#---------------interface---------------
w = Tk()
w.title("Lorenz")
w.geometry('800x600')
frame = tk.Frame(w)
frame.pack()
button1 = tk.Button(w, text='draw', fg='red', command= lambda : button_add())
button1.pack(side=tk.LEFT)
w.mainloop()

使用tkinter嵌入matplotlib图时,应使用matplotlib.figure.Figure而不是plt.figureFigurecanvasax的创建顺序也很重要:

def button_add():
...
# Plot
fig = Figure()
canvas = FigureCanvasTkAgg(fig, w)
canvas.draw()
ax = fig.add_subplot(111, projection="3d")
ax.plot(xs, ys, zs, lw=0.5)
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("Lorenz Attractor")
toolbar = NavigationToolbar2Tk(canvas, w)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
...

最新更新