[Tutor] passing values to a callback
Dave Angel
davea at davea.name
Sat Jul 13 20:34:29 CEST 2013
On 07/13/2013 01:48 PM, Alan Gauld wrote:
> 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, ....)
Whoops. Brett had chained the reference with his call to grid(), so
this would store a None. The line needs to be split up:
self.entry1 = Entry( frame, bg = "white", width = 3 )
self.entry1.grid(row = 0, column = 0 )
Otherwise, Alan's answer is right-on.
If you want to give an initial string value, then add:
self.entry1.insert(0, "42")
>
>> 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
--
DaveA
More information about the Tutor
mailing list