Tkinter, StringVar and dict
Kevin Walzer
kw at codebykevin.com
Fri Dec 22 18:34:22 EST 2006
James Stroud wrote:
> Kevin Walzer wrote:
>> I'm trying to manage user preferences in a Tkinter application by
>> initializing some values that can then be configured from a GUI. The
>> values are set up as a dict, like so:
>>
>> self.prefs= {
>> 'interface': '-en1',
>> 'verbose': '-v',
>> 'fontname': 'Courier',
>> 'point': 12,
>> }
>>
>> To link these values to the appropriate Tkinter variables, I'm using
>> code like this:
>>
>> self.prefs['interface'] = StringVar()
>> self.prefs['interface'].set("-en0") # initialize
>>
>> This raises an error in Tkinter:
>>
>> Exception in Tkinter callback
>> Traceback (most recent call last):
>> File
>> "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tkinter.py",
>> line 1403, in __call__
>> return self.func(*args)
>> File
>> "/Users/kevin/Programming/packetstream/packetstream-classes.py", line
>> 293, in setPrefs
>> self.prefs['interface'] = StringVar()
>> File
>> "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tkinter.py",
>> line 3237, in __setitem__
>> self.tk.call(self.name, 'configure', '-'+key, value)
>> TclError: unknown option "-interface"
>>
>> Can someone help me smooth this out--to get dict key-values into a
>> Tkinter variable like StringVar()?
>>
>> Thanks.
>>
>
> I overlooked this latter question.
>
> Probably, your naming confusion above with self.prefs and the resulting
> errors obscure your intention. But, were I to keep a dictionary of
> StringVars for prefs, I would initialize it in this manner:
>
> # somewhere in self
> defaults = {
> 'interface' : '-en1',
> 'verbose' : '-v',
> 'fontname' : 'Courier',
> 'point' : 12
> }
> self.prefs = dict((d,StringVar()) for d in defaults)
> for d in defaults:
> self.prefs[d].set(defaults[d])
>
> Note, of course, that you will need to access 'point' like this if you
> want it back as an int:
>
> int(self.prefs['point'].get())
>
> Because StringVars return strings from their get() method.
>
> James
>
Thanks, these snippets helped me work this out.
--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
More information about the Python-list
mailing list