a question about tkinter StringVars()

William Gill noreply at gcgroup.net
Wed Aug 24 12:10:56 EDT 2005



Eric Brunel wrote:
> On Wed, 24 Aug 2005 15:07:27 GMT, William Gill <noreply at gcgroup.net> wrote:
> 
>> Working with tkinter, I have a createWidgets() method in a class.
>> Within createWidgets() I create several StringVars() and
>> assign them to the textvariable option of several widgets.
>> Effectively my code structure is:
>>
>> def createWidgets(self):
>>      ...
>>      var = StringVar()
>>      Entry(master,textvariable=var)
>>      ...
>>      ...
>>
>> Though 'var' would normally go out of scope when createWidgets
>> completes, since the Entry and its reference do not go out of scope,
>> only the name 'var' goes out of scope, not the StringVar object, Right?
> 
> 
> Well, apparently not:
> 
> ------------------------------------------------
> from Tkinter import *
> 
> class MyStringVar(StringVar):
>   def __del__(self):
>     print "I'm dying!"
> 
> root = Tk()
> 
> def cw():
>   var = MyStringVar()
>   Entry(root, textvariable=var).pack()
> 
> cw()
> 
> root.mainloop()
> ------------------------------------------------
> 
> Running this script actually prints "I'm dying!", so there is obviously 
> no reference from the Entry widget to the variable object. The reference 
> is actually kept at tcl level between an entry and the *tcl* variable, 
> which knows nothing about the *Python* variable.
I will have to do some experimenting.
> 
> BTW, the whole purpose of StringVar's is to be kept so that the text for 
> the entry can be retrieved or modified by another part of the program. 
> So what can be the purpose of creating variables in a function or method 
> and not keeping them anywhere else than a local variable?
I was trying to keep my question simple.
In actuality,  I have a widget I'll call dataForm that extends 
tkSimpleDialog.Dialog.  In it I have several entry and checkbox widgets, 
and a call to a changed() method passed from the parent.  When I'm done 
editing dataForm, all the variables are processed in a save() method, 
and dataForm is destroyed.

What happened when I used self.var = MyStringVar() and Entry(root, 
textvariable=self.var).pack(), is that a subsequent call to create a 
dataForm instance has residual data from the previous instance AND the 
change callback caused an error.  Changing to local variables seemed to 
cure the problems.

I just tried changing back to the self.var approach, and it seems to 
work fine???  I must have had some name conflicts in my earlier code. 
I'll try to figure it out, and post if I do.

Bill





More information about the Python-list mailing list