简体   繁体   中英

Button returning specific string [Tkinter]

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM