3

I am trying to assign values to buttons which return their value when clicked (more precisely, they print it.) The only caveat is that the buttons are created dynamically, using a for loop.

How can I assign id's (and other variables) to buttons which have been created with a for loop?

Example Code:

#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 Answer 1

8

The problem is that you are using the last value of self.button_id when you call the command once the buttons are created. You have to bind the current value of the local variable for each lambda with lambda i=i: do_something_with(i):

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.