Button returning specific string [Tkinter]

Question:

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!

Asked By: user3404844

||

Answers:

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.

Answered By: alecxe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.