plumburp
plumburp

Reputation: 3

Is there a better way of identifying buttons created in a for loop?

Before I start I want to clarify that I'm a newcomer to not only python but programming as a whole.

Here is my code:

def function(pressed):
    print(pressed)


root = tk.Tk()
root.geometry("")

thelist = []


for i in range(10):
    thelist.append(tk.Button(root, text="button {}".format(i+1), command=lambda a=i: function(thelist[a])))
    thelist[i].grid(row=i, column=0)



root.mainloop()

What I want to be able to do is to identify each of the buttons. When printing them as shown in the function, it gives values like ".!button", ".!button2", ".!button3" and so on. What I have thought to do here is use try except statements, similar to what is shown below, but obviously on forms with many buttons this could become problematic.

try:
    btnNumber = int(str(pressed))[8:]
except:
    btnNumber = 1

There is definitely a better way to do this. Any help would be appreciated.

Upvotes: 0

Views: 44

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386342

If your goal is to get the button number, the better way is to pass the number into your function rather than the button instance.

def function(btn):
    print(btn)

for i in range(10):
    thelist.append(tk.Button(root, text="button {}".format(i+1), command=lambda btn=i: function(btn))

Upvotes: 1

Related Questions