0

I want to create some buttons in tkinter with a for loop that run a function with a parameter but when I click on the buttons they all output else. I don't know what went wrong, here is my code:

statements = ['print', 'if', 'else']

def ins(state):
  print(state)

  return

count = 0

for x in statements:
  b = Button(self.funcFrame, text=x, command=lambda:ins(x))
  b.grid(row=0, column=count)
  count += 1

Thank you!

quamrana
  • 37,849
  • 12
  • 53
  • 71
Chiz
  • 7
  • 2

1 Answers1

0

When you create buttons in a for loop you can't use command directly. To make it work you should use partial


from functools import partial

statements = ['print', 'if', 'else']

def ins(state):
    print(state)
    return


for count, x in enumerate(statements):
    b = Button(self.funcFrame, text=x, command=partial(ins, x))
    b.grid(row=0, column=count)

CarlosSR
  • 1,145
  • 1
  • 10
  • 22