Hello I'm making a GUI with tkinter and with matplotlib embeded. I have a FigureCanvas that I use to graph various things depending on the users inputs. Everything seems to work fine excepts for a weird error that doesn't seems to have much of an impact. Here is the code:
import tkinter as tk
import tkinter.ttk as ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
class App:
def __init__(self, root):
self.root = root
#
self.combo = ttk.Combobox(root, values=["2D 1", "2D 2", "3D"], state = "readonly")
self.combo.bind("<<ComboboxSelected>>", self.change_graph)
self.combo.pack()
#
self.fig = Figure()
self.ax = self.fig.add_subplot()
self.drawing_area = FigureCanvasTkAgg(self.fig, master=root)
self.drawing_area.get_tk_widget().pack()
#
self.axis_3D = False
def change_graph(self, event):
graph_selected = self.combo.get()
if graph_selected == "2D 1":
if self.axis_3D:
self.ax.remove()
self.ax = self.fig.add_subplot()
self.axis_3D = False
else:
self.ax.clear()
x = np.linspace(0, 10, 100)
y = 4 + 2 * np.sin(2 * x)
self.ax.plot(x, y, c="r")
self.ax.axis("equal")
self.drawing_area.draw()
elif graph_selected == "2D 2":
if self.axis_3D:
self.ax.remove()
self.ax = self.fig.add_subplot()
self.axis_3D = False
else:
self.ax.clear()
x = np.linspace(0, 10, 500)
y = -4 + 2 * np.sin(2 * x)
self.ax.plot(x, y, c="b")
self.ax.axis("auto")
self.drawing_area.draw()
else:
if self.axis_3D:
self.ax.clear()
else:
self.ax.remove()
self.ax = self.fig.add_subplot(projection="3d")
self.axis_3D = True
x = np.linspace(0, 10, 500)
y = 4 + 2 * np.sin(2 * x)
z = 2*x
self.ax.plot(x, y, z, c="b")
self.drawing_area.draw()
root = tk.Tk()
root.geometry("800x600")
app = App(root)
root.mainloop()
The problem I'm having is that after the 3D graph is selected and then a 2D graph is selected back, every time the graph is panned it gives an error which I don't understand. The error is the following:
Traceback (most recent call last):
File "...\matplotlib\cbook\__init__.py", line 287, in process
func(*args, **kwargs)
File "...\mpl_toolkits\mplot3d\axes3d.py", line 1165, in _button_release
toolbar = getattr(self.figure.canvas, "toolbar")
AttributeError: 'NoneType' object has no attribute 'canvas'