Creating Button arrays with different commands using Tkinter
Fredrik Lundh
fredrik at pythonware.com
Tue Feb 22 11:04:23 EST 2005
"Harlin" <harlinseritt at yahoo.com> 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>
More information about the Python-list
mailing list