how to pass the text entered in entry box in tkinter from one function to another?
<p>I m tying to pass the entery box text from one function to another but it gives me error that the variable itself is not defined.Here is my code.</p>

<pre><code>from Tkinter import *
def mhello():
    mtext=ment.get()
    print mtext
def main():
    root=Tk()
    ment=StringVar()
    root.title('Test')
    mlabel=Label(root,text='Enter Text').pack()
    mentry=Entry(root,textvariable=ment).pack() 
    mbutton=Button(root,text='Click Me',command=mhello).pack()
if __name__ == '__main__':
    main()
</code></pre>

<p>it gives the error as:</p>

<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__
return self.func(*args)
File "pygui.py", line 3, in mhello
mtext=ment.get() 
NameError: global name 'ment' is not defined
</code></pre>

<p>First off you have a variable scope issue, variables defined in functions are local to those functions so <code>ment</code> is defined in <code>main</code> but not in <code>mhello</code>. Either pass the variable in to <code>mhello</code> or make <code>ment</code> a global. So we can pass in the variable like this:</p>

<pre><code>def mhello(var):
    mtext=var.get()
    print(mtext)
</code></pre>

<p>Then we need to call this from our button:</p>

<pre><code>mbutton=Button(root, text='Click Me', command=lambda: mhello(ment)).pack()
</code></pre>

<p>And we need to actually call the <code>mainloop</code> for the code to run properly:</p>

<pre><code>root.mainloop()
</code></pre>

<p>Without that no GUI will be run.</p>

<p>On a design level I usually create classes to store the variables that are in the same parts of the GUI to avoid needing to pass a lot of parameters around.</p>

python python-2.7 tkinter