Re: Creating Button arrays with different commands using Tkinter

2005-02-23 Thread Harlin Seritt
Thanks Frederik. I knew it was not binding the way I intended to, but
just had no idea why or how to make it do so... thanks for the quick
lambda lesson :-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Creating Button arrays with different commands using Tkinter

2005-02-22 Thread Harlin
I have an array of Appnames. Let's say they are 'Monkeys', 'Cats',
'Birds'.

I would like create a button array with these:

---Start Code---
# Constructing and displaying buttons
for a in Appnames:
   Button(root, text=a, command=lambda:self.OpenFile(a)).pack()

# Somewhere else I have this function defined within the class...
def OpenFile(self, AppName):
   fh = open(AppName+.txt, 'r').read()
   do something with fh

---End Code---

When I do this, whatever the last value a was is what the each button's
command option is. Does anyone know what I can do to differentiate each
button so that it has its own separate argument for self.OpenFile?

Thanks,

Harlin

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating Button arrays with different commands using Tkinter

2005-02-22 Thread Fredrik Lundh
Harlin [EMAIL PROTECTED] wrote

I have an array of Appnames. Let's say they are 'Monkeys', 'Cats',
 'Birds'.

 I would like create a button array with these:

 ---Start Code---
 # Constructing and displaying buttons
 for a in Appnames:
   Button(root, text=a, command=lambda:self.OpenFile(a)).pack()

 # Somewhere else I have this function defined within the class...
 def OpenFile(self, AppName):
   fh = open(AppName+.txt, 'r').read()
   do something with fh

 ---End Code---

 When I do this, whatever the last value a was is what the each button's
 command option is.

that's how lexical scoping works: you're passing in the value a has
when you click the button, not the value it had when you created the
lambda.

 Does anyone know what I can do to differentiate each
 button so that it has its own separate argument for self.OpenFile?

bind to the object instead of binding to the name:

for a in Appnames:
Button(root, text=a, command=lambda a=a: self.OpenFile(a)).pack()

/F 



-- 
http://mail.python.org/mailman/listinfo/python-list