问题
I am opening a matplotlib pyplot in a tkinter window with the below code. My issue is that the plot is still popping up in the matplotlib window as well, and I don't know how to stop that. I've tried commenting out each of the plt.plot's but that didn't help.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import Tkinter as Tkinter
def tester():
class window(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.grid_rowconfigure(0,minsize=50)
self.grid_rowconfigure(1,minsize=5)
self.grid_rowconfigure(2,minsize=500)
self.grid_rowconfigure(3,minsize=5)
self.grid_rowconfigure(4,minsize=20)
self.grid_columnconfigure(0,minsize=5)
self.grid_columnconfigure(1,minsize=800)
self.grid_columnconfigure(2,minsize=5)
framer = Tkinter.Frame(self, borderwidth=2, relief='groove',bg='white')
framer.grid(column=0,row=1,columnspan=3,rowspan=3, sticky='NSEW')
Button1 = Tkinter.Button(bg='red',text="Click Me",command=self.onbutton1)
Button1.grid(column=1,row=0,sticky='NSEW')
def onbutton1(self):
array = np.array([[1,2,3,2,1],[2,3,4,3,2],[3,4,5,4,3],[4,5,6,5,4],[3,4,5,4,3]])
maximum = np.max(array)
index_max = np.where(array == maximum)
max_a, max_b = index_max
plotter=plt.figure('plot')
plt.contour(array, linewidths = 1, colors = 'k')
plt.contourf(array, cmap = plt.cm.jet)
plt.ylabel('y', fontdict = {'fontsize':16})
plt.xlabel('x', fontdict = {'fontsize':16})
plt.colorbar()
plt.title('Title', fontdict = {'fontsize':20})
plt.plot(max_b, max_a, 'wo')
F_canvas = FigureCanvasTkAgg(plotter, self)
F_canvas.get_tk_widget().grid(column=1,row=2)
if __name__ == "__main__":
app = window(None)
app.title('Window')
app.mainloop()
tester()
Can anyone be my hero?
回答1:
If you want to manage all the windows yourself, you should not use pyplot at all. When you do plt.figure
, for instance, it is creating a matplotlib-managed figure window.
Don't even import pyplot. Exactly how to adapt your code will vary depending on what matplotlib features you use, but, for instance, to create the figure you'll want to do:
from matplotlib import figure
plotter = figure.Figure()
You'll access most of the plot types (such as contour
) by accessing an Axes object of that Figure and using its methods (e.g., if you have an axes ax
you can cal ax.contour
).
See this example for a simple demo of how to embed matplotlib in a Tkinter app.
来源:https://stackoverflow.com/questions/25839795/opening-a-plot-in-tkinter-only-no-matplotlib-popup