在Tkinter中动态创建函数和绑定按钮

时间:2013-07-20 00:32:13

标签: python dynamic tkinter

我正在尝试为按钮分配值,这些按钮在单击时返回它们的值(更确切地说,它们打印它。)唯一需要注意的是按钮是使用for循环动态创建的。

如何将id(和其他变量)分配给使用for循环创建的按钮?

示例代码:

#Example program to illustrate my issue with dynamic buttons.

from Tkinter import *

class my_app(Frame):
    """Basic Frame"""
    def __init__(self, master):
        """Init the Frame"""
        Frame.__init__(self,master)
        self.grid()
        self.Create_Widgets()

    def Create_Widgets(self):

        for i in range(1, 11): #Start creating buttons

            self.button_id = i #This is meant to be the ID. How can I "attach" or "bind" it to the button?
            print self.button_id

            self.newmessage = Button(self, #I want to bind the self.button_id to each button, so that it prints its number when clicked.
                                     text = "Button ID: %d" % (self.button_id),
                                     anchor = W, command =  lambda: self.access(self.button_id))#Run the method

            #Placing
            self.newmessage.config(height = 3, width = 100)
            self.newmessage.grid(column = 0, row = i, sticky = NW)

    def access(self, b_id): #This is one of the areas where I need help. I want this to return the number of the button clicked.
        self.b_id = b_id
        print self.b_id #Print Button ID

#Root Stuff


root = Tk()
root.title("Tkinter Dynamics")
root.geometry("500x500")
app = my_app(root)

root.mainloop()

1 个答案:

答案 0 :(得分:6)

问题是,在创建按钮后调用命令时,您使用的是self.button_id的最后一个值。您必须使用lambda i=i: do_something_with(i)

绑定每个lambda的局部变量的当前值
def Create_Widgets(self):
    for i in range(1, 11):
        self.newmessage = Button(self, text= "Button ID: %d" % i, anchor=W,
                                 command = lambda i=i: self.access(i))
        self.newmessage.config(height = 3, width = 100)
        self.newmessage.grid(column = 0, row = i, sticky = NW)