[Tutor] Please Critque Tkinter Class for Newbie

Michael P. Reilly arcege@speakeasy.net
Thu, 12 Jul 2001 16:21:29 -0400 (EDT)


Sheila King wrote
> <arcege@speakeasy.net>  wrote about Re: [Tutor]
> :The colorInfo widget gets passed a StringVar instance, but the
> :default is a (empty) string.  The system might get a little
> :confused: Tk (under Tkinter) uses the name of the variable,
> :the default string could be taken without an error, but lead to
> :some odd problems.  You probably want to test before using the
> :value and if not value, then possibly raise an exception or create
> :a new variable.
> 
> OK, I'm working on understanding the issue, here. I guess I didn't
> really understand the distinction between the text and textvariable
> being string vs. StringVar types, and it must've completely passed over
> my head, that the option on the Entry widget is a textvariable (requires
> a Tkinter variable class).

It's a little complicated - it deals with the interactions between Python,
Tcl (the language Tk works with) and Tk (which is under Tkinter).

Try this experiment:
>>> from Tkinter import *
>>> root = Tk()
>>> sv = StringVar(root)
>>> str(sv)
'PY_VAR0'
>>> sv.get()
''
>>> root.setvar('PY_VAR0', 'hi there')
>>> sv.get()
'hi there'
>>> e = Entry(root, textvariable='PY_VAR0')
>>> e.pack()
>>> mainloop()

Now look at the contents of the entry widget in the window.  It will
say "hi there".  That's because the StringVar instance is setting the
Tcl variable PY_VAR0 which the Tk entry widget is using.  The Tkinter
textvariable option takes the str() of the Variable instance (StringVar,
IntVar, etc.) which is the name.

> I guess there is no recommended way to pass default parameters to
> Tkinter variables such as the StringVar type (and IntVar and DoubleVar)?

Nope, the Variable subclasses do not take default arguments to the
constructor... unless you would like to further subclass them.

class StringVarDef(StringVar):
  _default = 'this is an empty string'
class IntVarDef(IntVar):
  _default = 42

This will set up the new default value for that class (not the instances).

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |