When I insert a matplotlib figure in my tkinter window, when I start my program, extra popup windows appear. They do not affect the functionality of my GUI, but they are a bit annoying.
I have written a basic script that shows the problem. I run this through Spyder:
import tkinter as tk
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.pyplot import figure as Figure
from matplotlib import pyplot as plt
class MyGUI(tk.Tk):
def __init__(self,master):
self.f=Figure(figsize=(5,5),dpi=100)
self.fig, self.ax= plt.subplots()
self.canvas = FigureCanvasTkAgg(self.fig,master)
self.toolbar=NavigationToolbar2Tk(self.canvas,master)
#self.toolbar.update()
self.canvas._tkcanvas.pack(padx=20, pady=20)
root =tk.Tk()
window=MyGUI(root)
root.mainloop()
When I run this, I get three windows. One is the root window that shows an empty graph and a toolbar (labeled 'tk'). This is the only window that I want. Then I get a 'Figure 1' window with a toolbar and a 'Figure 2' window with a graph and toolbar. 
From commenting out the second half of the init method, it looks like the problem comes from this part.
self.f=Figure(figsize=(5,5),dpi=100)
self.fig, self.ax= plt.subplots()
self.canvas = FigureCanvasTkAgg(self.fig,master)
However, I am quite new to object oriented programming and tkinter, and therefore not experienced enough to figure out what the mistake is. Any ideas?
You are creating two figures. One of them is created via pyplot. One shouldn't try to embedd a pyplot figure inside a custom GUI. Remove pyplot completely and create only a single figure.
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
class MyGUI(tk.Tk):
def __init__(self,master):
self.fig=Figure(figsize=(5,5),dpi=100)
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.fig,master)
self.toolbar=NavigationToolbar2Tk(self.canvas,master)
#self.toolbar.update()
self.canvas._tkcanvas.pack(padx=20, pady=20)
root =tk.Tk()
window=MyGUI(root)
root.mainloop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With