按钮返回特定字符串[Tkinter]

时间:2014-03-26 03:45:07

标签: python python-2.7 tkinter

我目前有一个Tkinter,它显示多个名称作为标签。

每个标签的右侧都有一个名为“Foo”的按钮,点击后,

它将调用一个需要单击按钮左侧标签名称的函数。

这就是我创建按钮和标签的方式:

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

如果点击Foo旁边的Mark按钮,该怎么办?按钮将返回标签名称Mark。其他标签旁边的其他Foo按钮也是如此。

谢谢!

1 个答案:

答案 0 :(得分:1)

以下是您可以这样做的方法:

以下是代码:

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

注意索引是如何传递给lambda的,这就是所谓的“lambda闭包范围”问题,请参阅Python lambda closure scoping

希望有所帮助。