[Tutor] Raiobutton question

Michael P. Reilly arcege@shore.net
Sun, 11 Feb 2001 10:15:19 -0500 (EST)


> The problem is that when we construct an InvVar(), Tk expects us to have a
> root window already set up.  The line:
> 
>     root = Tkinter.Tk()
> 
> initializes _tk to something that all other widgets will depend
> on.  So, when we do something like:
> 
> ###
> root = Tkinter.Tk()
> button = Tkinter.Button()
> ###
> 
> in the background, the Button() knows that it should connect up with root,
> because the _tk variable's initialized.
> 
> 
> Going back to your program, the IntVar definition is a bit too early;
> IntVar doesn't know where to attach to until we either make a root window.  
> Try putting it after your Tk() call, and you should be ok.

The reason is a little more subtle than this.  All _widgets_ will
implicitly create a new Tk() instance if None is set (and if Tkinter.
_support_default_root is true).  However the Variable classes (of
which IntVar is a subclass) are not widgets, and do not have this
behavior.

So where just
  python -c 'import Tkinter; Tkinter.Button()'
creating a widget with no Tk would work, but creating a variable before
a widget won't
  python -c 'import Tkinter; Tkinter.IntVar()'

The Button initialization detects that there is no _default_root
and creates a Tk instance (which sets _default_root);  but IntVar
does nothing like this, and expects _default_root to be set
already.

Glen, Grayson's "Python and Tkinter Programming" example that I assume
you are using (pp. 37-38) does not set "root = Tk()" at all, but uses
the root in the Radiobutton call.  This is confusing, and Grayson does
not really explain the Variable classes well at all.  Unfortunately, a
lot of the Tkinter documentation does not do this part of Tkinter
justice either.

> To tell the truth, I have no clue what an InvVar is.  But if you ever see
> something that says "_Tk is undefined", it's probably because a Tk()
> instance hasn't been built yet.

Tkinter is written on top of Tcl/Tk, which has its own variables and
functions, so there are such classes as Variable, and its subclasses,
and CallWhapper so Tk can use Python functions and map Tcl variables to
Python names.  Much of this is handled for you in Tkinter itself, but
for "shared" variables like Radiobutton instances required a new form
of object.

> (Someday, I shall have to take a look at "Python and Tkinter Programming",
> and really understand what's happening... *grin*)

It's a very good book, I recommend getting it.  I would suggest reading
Fredrik Lundh's not-as-complete "An Introduction to Tkinter" as well
  <URL: http:/www.pythonware.com/library/tkinter/introduction/>

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------