2

I currently have a Tkinter that displays multiple names as label.

The right side of every labels has a button named "Foo" and when clicked,

it will invoke a function that needs the name of the label on the left of the button that was clicked.

This is how I created the button and the label:

from Tkinter import *
class display():
    def __init__(self):
        self.namelist = ["Mike","Rachael","Mark","Miguel","Peter","Lyn"]
    def showlist(self):
        self.controlframe = Frame()
        self.controlframe.pack()
        self.frame = Frame(self.controlframe,height=1)
        self.frame.pack()
        row = 0
        for x in self.namelist:
            label = Label(self.frame,text="%s "%x,width=17,anchor="w") #limit the name to 17 characters
            fooButton = Button(self.frame,text="Foo")
            label.grid(row=row, column=0, sticky="W")
            fooButton.grid(row=row, column=1)
            row = row + 1
        mainloop()
D = display()
D.showlist()

How do I do something like if I click the Foo button next to Mark then the button will return the name of the label, Mark. The same goes for other Foo buttons next to other labels.

Thanks!

1
  • where's the code where you tried to grab the label & you failed? Commented Mar 26, 2014 at 3:47

1 Answer 1

1

Here's how you can do it:

Here's the code:

from Tkinter import *


class display():
    def __init__(self, controlframe):
        self.controlframe = controlframe
        self.namelist = ["Mike", "Rachael", "Mark", "Miguel", "Peter", "Lyn"]

    def callback(self, index):
        print self.namelist[index]

    def showlist(self):
        self.frame = Frame(self.controlframe, height=1)
        self.frame.pack()
        row = 0
        for index, x in enumerate(self.namelist):
            label = Label(self.frame, text="%s " % x, width=17, anchor="w") #limit the name to 17 characters
            fooButton = Button(self.frame, text="Foo", 
                               command=lambda index=index: self.callback(index))
            label.grid(row=row, column=0, sticky="W")
            fooButton.grid(row=row, column=1)
            row = row + 1


tk = Tk()

D = display(tk)
D.showlist()
tk.mainloop()

Note how the index is passed to the lambda, this is so called "lambda closure scoping" problem, see Python lambda closure scoping.

Hope that helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh my goodness... Thank you so much for quick and precise answer!
Then do you know how to delete the specific label when the button is clicked?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.