Assign a command to my Tkinter buttons by looping over them

Question:

I would like to use a forloop to give my buttons a function in Tkinter. When I do it like this I get an error message, that those buttons are not defined. I tried several solution, but it did not work. I would be happy, if you could help me, as I am trying to make a calculator.

This is how the loop looks like:

for s in range(0, 10):
    def add_(s):
         entry_box.insert(1000, str(number))

And this is how i made a button:

button_zero = Button(main_window, text='0', padx=30, pady=25, command=add_0)
button_zero.place(x=67,y=430)
Asked By: gabri2503

||

Answers:

Based on the information you provided your the command argument in button isn’t equal to any defined function. Maybe just a typo:

for s in range(0,10):
    def add_0(s):
        entry_box.insert(1000,str(number))
Answered By: Andre Wallin

If you have 10 buttons (0-9) that all insert a number into entry_box, I would make a function factory.

def add_(s):
    def wrapped():
        entry_box.insert(1000, s)
    return wrapped

When you call add_(2), you get as a return a function that, when called, adds 2 to the entry box.

add_2 = add_("2")
add_2()  # adds 2 to the entry box, returns None

Then you can iterate through your buttons and assign a command to each.

for i, button in enumerate([button_zero, button_one, button_two, ...]):
    button.configure(command=add_(str(i)))
Answered By: Adam Smith