嵌入 matplotlib 和 tkinter

Embeded matplot3d and tkinter

我想在 Tkinter Frame 中连续绘制(生成 3 个随机数并使用动画绘制)。

代码:

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
from mpl_toolkits.mplot3d import Axes3D
import tkinter as tk
from tkinter import ttk
from random import randint

style.use("ggplot")

f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111, projection='3d')
xList = []
yList = []
zList = []

def animate(i):


    x = randint(2,9)
    if x == 4:
        xList.clear()
        yList.clear()
        zList.clear()


    xList.append(x)
    yList.append(randint(2,9))
    zList.append(randint(2,9))

    a.plot(xList,yList,zList)


class Qut(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        container = tk.Frame(self)
        container.pack(side = "top", fill="both",expand = True)
        tk.Tk.wm_title(self, '3D Painter')
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)

        self.frames = {}
        for F in (StartPage,PageOne):
            frame = F(container,self)
            self.frames[F] = frame
            frame.grid(row = 0 , column = 0 , sticky = "nsew")
        self.show_frame(StartPage)

    def show_frame(self,cont):
        frame = self.frames[cont]
        frame.tkraise()



class StartPage(tk.Frame):
    def __init__(self,parent,controller):
        tk.Frame.__init__(self, parent)
        label = ttk.Label(self,text='hi')
        label.pack(pady=10,padx=10)
        button = ttk.Button(self,text='PageOne',command=lambda:controller.show_frame(PageOne))
        button.pack()



class PageOne(tk.Frame):
    def __init__(self,parent,controller):
        tk.Frame.__init__(self, parent)
        label1 = ttk.Label(self,text='Graph Page')
        label1.pack(pady=10,padx=10)
        button1 = ttk.Button(self,text='Home',command=lambda:controller.show_frame(StartPage))
        button1.pack()


        canvas = FigureCanvasTkAgg(f,self)
        canvas.show()
        canvas.get_tk_widget().pack(side = tk.TOP , fill=tk.BOTH,expand = True)
        toolbar = NavigationToolbar2TkAgg(canvas,self)
        toolbar.update()

app = Qut()
an = animation.FuncAnimation(f,animate,interval=1000)
app.mainloop()

有两个错误,第一个是我无法使用鼠标旋转 3D canvas,我得到了这个错误:

UserWarning: Axes3D.figure.canvas is 'None', mouse rotation disabled. Set canvas then call Axes3D.mouse_init(). warnings.warn('Axes3D.figure.canvas is \'None\', mouse rotation disabled. Set canvas then call Axes3D.mouse_init().')

第二个错误:

TypeError: can't multiply sequence by non-int of type 'float'

mouse_init 必须应用于 ax 对象

a.mouse_init()

之前可以使用a.clear()清除之前的图形