[Tutor] passing values to a callback

Alan Gauld alan.gauld at btinternet.com
Sat Jul 13 19:48:41 CEST 2013


On 13/07/13 16:08, Brett Wunderlich wrote:

> commanded by a Button. Once the button is pressed the values in the
> fields should result in a calculation - the values should all be numeric

You'll need to convert between strings and numbers, the GUI displays 
strings (with one exception, see below)

> class App:
>
>      def __init__( self, master ):
>          frame = Frame( master )
>          frame.grid()
>          entry1 = Entry( frame, bg = "white", width = 3 ).grid(row = 0,
> column = 0 )

You want to store a reference to the entrey in your app so this should read:

            self.entry1 = Entry( frame, ....)

>      def calculate( self ):
>          print 1

Now you can access then entry objects using self

            print self.entry1.get()

Or convert to an int (or float) as required.

Finally you can write back to the entry widget the result string
           self.entry.insert(0,resultString)

This is a common requirement so there is a bit of magic that Tk
allows namely you can specify a StringVar or IntVar variable in
your GUI definition and link it to an entry. The Tk core will
then keep the content ogf the variable and widget in synch
(and do the int conversion if appropriate).

In your init method you can set up a StringVar using

       self.Entry1Var = StringVar()
       self.entry1['textvariable'] = self.Entry1Var

or an int var like:

       self.Entry2Var = IntVar()
       self.entry1['textvariable'] = self.Entry2Var


And you can read/change the value by get() or set()
actions on the variables.

There are also DoubleVar and BooleanVar available too.
You can use them on some other types of widgets, but not all.

Personally I don't find them that big a help and often just access the 
widget directly.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list