Creating Button arrays with different commands using Tkinter

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Harlin

    #1

    Creating Button arrays with different commands using Tkinter

    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

  • Fredrik Lundh

    #2
    Re: Creating Button arrays with different commands using Tkinter

    "Harlin" <harlinseritt@y ahoo.com> wrote
    [color=blue]
    >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.[/color]

    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.
    [color=blue]
    > Does anyone know what I can do to differentiate each
    > button so that it has its own separate argument for self.OpenFile?[/color]

    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>



    Comment

    • Harlin Seritt

      #3
      Re: Creating Button arrays with different commands using Tkinter

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

      Comment

      Working...