Creating Button arrays with different commands using Tkinter

H

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
 
F

Fredrik Lundh

Harlin said:
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>
 
H

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 :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top