schurr
schurr

Reputation: 46

Is there any way to create buttons in a for loop with the same function but with different attributes?

I'm trying to create several buttons so each one will activate the same function but with changing attributes. What probably happens, is that the value that I take from the for loop is the last one it generates. Here is the code:

from tkinter import Tk, Button

root = Tk()
root.geometry('500x500')

def add(num):
    print(num)
    return num + 5

num_list = [1, 2, 3, 4, 5]
for i in range(len(num_list)):
    Button(root, text=str(num_list[i]), command=lambda: print(add(num_list[i]))).place(x=350 ,y=250+i*20)

root.mainloop()

In the following code, no matter what button you click it will always send 5 as the value of I (the last value).

Upvotes: 1

Views: 388

Answers (1)

Rhys Flook
Rhys Flook

Reputation: 195

You can just add a variable to the lambda call, like so:

Button(root, text=str(num_list[i]), command=lambda i=i: print(add(num_list[i]))).place(x=350 ,y=250+i*20)

That i=i will make the program work how you want it, as it will make the function take the value of i when the button was created.

Upvotes: 2

Related Questions