[Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables

Alan Gauld alan.gauld at btinternet.com
Wed Mar 4 00:14:07 CET 2009

"Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote

> see my post of yesterday, "Maintaining the Same Variable 
> Type--Tkinter",
> went over like a lead balloon. :-)

Yeah, I had no idea what you meant :-)

>  I've heavily modified the original code to accept a config file,
> and set up variable to initialize the widgets, trying to bridge
> some code in the Enter_Data_Dialog and Set_Enter_Data
> objects control variable code is where the trouble lays

Yep, and part of it is the attempt to create variables dynamically.
It's so much easier if you use a dictionary or a list of name,value

> The code below puts up a window with one menu and two
> submenus items,  Enter Data, and Exit. Select Enter Data
> and put in an integer number. It all works fine.

It works with hard coded variable names. Trying to use dynamic
variable names will be much trickier!

> Basically, what I want to do is eliminate code like
> dialog.anumberVar.get() and replace it by constructing the
> appropriate names for the config file.

If you used a list of variables you could replace it with

self.varList[0][1] = dialog.myVar.get()

In this case, the config file might contain:
>    anumber = 123

and you store that as
varList.append( (varname, varValue) )

If there is only one variable at a time you could just use the
tuple of course:

self.myVar = (varname, varValue)

Then the dialog return becomes:

self.myVar[1] = dialog.myVar.get()

You also need to make the dialog smart enough to read
the name of the variable (myVar[0]) and set the label
accordingly... If you use dynamic variables you will need
to pass in the variable name and then use getattr to
retrieve the value. Or pass name and value - which
sounds a lot like a tuple?

The problem with trying to create actual variables is that
the rest of yor code must become psychic (or very complex)
to figure out what variable to use. Or you write a lott of
near identical code to handle every possible variable name!

> BTW, the Quit function is original but doesn't kill the window
> when Quit is used. What fixes that?

Brute force you can use sys.exit()!

But more normally you can use what you have used,
so I'm not sure why its not working!

> For more bonus points, it seems as though the try statement
> in the dialog should really bring up an "Error" dialog saying
> something is wrong, when an invalid entry occurs.

You can use the standard 'showerror' or 'showwarning' dialogs
for that:


Finally I note the use of eval() to evaluate the user input. That is 
bad bad. And looks like there is no need since after eval'ing you
then use int(). You should be able to use int() directly on the input
and handle any ValueError exceptions etc to catch bad input.


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list