Re: Tkinter StringVar mystery



On Mon, 2006-07-17 at 15:00 -0600, Bob Greschke wrote:
First off I have this class (thanks to whoever came up with this way back
when):

######################
# BEGIN: class Command
# LIB:Command():2006.110
# Pass arguments to functions from button presses and menu selections,
# bind's. Nice!
# In your declaration:
# ...command = Command(func, args,...)
class Command:
def __init__(self, func, *args, **kw):
self.func = func
self.args = args
self.kw = kw
def __call__(self, *args, **kw):
args = self.args+args
kw.update(self.kw)
apply(self.func, args, kw)
# END: class Command


Then in the setup part of an entry form I have:

# CHBCBarcodeLastVar is the variable for an Entry() field
Button(SubFrame, text = "Print Barcode", \
command = Command(test, "other", CHBCBarcodeLastVar.get(), \
"CHBC")).pack(side = LEFT)


Then this is a/the test function:

def test(What, BC, Where, e = None):
# Does print the correct value
print CHBCBarcodeLastVar.get()
# Does change the field on the form
CHBCBarcodeLastVar.set("55555")
# BC is ""
print ":"+What+":", ":"+BC+":", ":"+Where+":"
return

Everything works as it should, except when the Button is clicked BC is an
empty str in test(). How come? (I really have NO clue how that Command
class works, but I use it like crazy. Is it the problem?)

The problem is when you are creating the "Print Barcode" button. Think
about what the value of CHBCBarcodeLastVar.get() is when you create the
button ? I bet it is an empty string. This value will always be passed
to test, regardless of how it changes in the future. What you probably
want is to pass the StringVar reference and then do a get in test.

Eg:

# CHBCBarcodeLastVar is the variable for an Entry() field
Button(SubFrame, text = "Print Barcode", \
command = Command(test, "other", CHBCBarcodeLastVar, \
"CHBC")).pack(side = LEFT)

def test(What, BC, Where, e = None):
print ":"+What+":", ":"+BC.get()":", ":"+Where+":"
return

Regards,

John



--
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

.


Quantcast