[Tex/LaTex] Tikz picture in beamer problem

beamererrorstikz-pgf

I have the following Latex code for a Tikz commutative diagram that renders correctly in a normal Latex document written in Overleaf. I am trying to create a Beamer slide presentation in Overleaf that includes the same Tikz diagram. but if I try to include the diagram on a beamer slide I receive an uncontrolled error concerning the \end{frame} part of the code for that slide right before the \end{document}. The issue only happens when I try to include the diagram. I tried compiling in TexShop and also had no success. Thanks for your help in advance. The code for the Beamer slide is below:

\documentclass{beamer}
\mode<presentation>
{
  \usetheme{default}      % or try Darmstadt, Madrid, Warsaw, ...
  \usecolortheme{default} % or try albatross, beaver, crane, ...
  \usefonttheme{default}  % or try serif, structurebold, ...
  \setbeamertemplate{navigation symbols}{}
  \setbeamertemplate{caption}[numbered]
} 
\usepackage{amsmath,amssymb,amsfonts,amscd}
\usepackage{tikz}
\usepackage{amssymb}
\usetikzlibrary{arrows,positioning}
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage[utf8x]{inputenc}
\usepackage{multicol}
\usepackage{tikz}
\usepackage{parskip}
\usepackage{listings}
\usepackage{multicol}
\usepackage{pgf}
\usetikzlibrary{arrows}
\usetikzlibrary {positioning}
\definecolor {processblue}{cmyk}{0.96,0,0,0}

\begin{document}

\begin{frame}
\usetikzlibrary{matrix}
\begin{center}
\begin{tikzpicture}
  \matrix (m) [matrix of math nodes,row sep=3em,column sep=4em,minimum width=2em]
  {
     E & E \\
     P & P \\};
  \path[-stealth]
    (m-1-1) edge node [left] {$\pi$} (m-2-1)
            edge node [above] {$\psi$} (m-1-2)
    (m-2-1.east|-m-2-2) edge node [below] {}
            node [above] {$\bar{\psi}$} (m-2-2)
    (m-1-2) edge node [right] {$\pi$} (m-2-2);
\end{tikzpicture}  
\end{center}
\end{frame}

\end{document}

Best Answer

A fragile frames helps:

\documentclass{beamer}

\usepackage{tikz}
\usetikzlibrary{arrows}
\usetikzlibrary{positioning}
\usetikzlibrary{matrix}


\begin{document}

\begin{frame}[fragile]
\begin{center}
    \begin{tikzpicture}
      \matrix (m) [matrix of math nodes,row sep=3em,column sep=4em,minimum width=2em]
      {
         E & E \\
         P & P \\};
      \path[-stealth]
        (m-1-1) edge node [left] {$\pi$} (m-2-1)
                edge node [above] {$\psi$} (m-1-2)
        (m-2-1.east|-m-2-2) edge node [below] {}
                node [above] {$\bar{\psi}$} (m-2-2)
        (m-1-2) edge node [right] {$\pi$} (m-2-2);
    \end{tikzpicture}  
\end{center}
\end{frame}

\end{document}

enter image description here