Getting value from Tkinter entry widget: variable scope difficulty
Hendrik van Rooyen
mail at microcorp.co.za
Mon Nov 20 01:12:15 EST 2006
"Kevin Walzer" <kw at kevin-walzer.com>
> I'm trying to construct a simple Tkinter GUI and I'm having trouble with
> getting the value of an entry widget and passing it onto a callback
> function. But I'm not grokking variable scope correctly.
>
> I have two functions. Here are the relevant excerpts:
>
> def makeGUI():
>
> ###lots of code to set up toplevel windows
>
> searchbutton=Button(topframe, image=searchglass, command=doSomething)
> searchbutton.image=searchglass
> searchbutton.pack(side=LEFT, expand = NO)
>
> searchterm=StringVar()
this will make a new local variable - if you want to assign to the global one,
you need to add a global statement before doing this, in this makeGUI function.
- you can read the global here if you have defined searchterm in an outer scope,
but the assign will make a new local one.
>
> entryterm=Entry(topframe, textvariable=searchterm)
> entryterm.pack(side=RIGHT)
>
> entrylabel=Label(topframe, text="Search:")
> entrylabel.pack(side=RIGHT)
>
>
> def doSomething():
>
> file = os.popen('systemcommand %s' % searchterm, 'r')
here searchterm seems to be a command line variable.
look in the help for sys.argv how to access command line variables
- not that you need to, but its good to know... :-)
had makeGUI been a class instead of a function, you could have
written makeGUI.searchterm here, without mucking around with globals....
>
> print searchterm
>
> ---
>
> What I want to happen is the value of searchterm to be passed on to the
> doSomething() call when the searchbutton is pressed. Right now it
> appears the value of "searchterm" is local to each function.
>
True
> In Tcl this would be handled by simply assigning the variable
> "searchterm" to the global namespace in each function, i.e. "global
> searchterm." I've looked and can't quite figure out how to do this in
> Python. Any advice is appreciated.
global searchterm # - in outer scope
global searchterm # - in inner scope before assign
HTH - Hendrik
More information about the Python-list
mailing list