0

I have a for loop which creates an amount of buttons (in tkinter) based on the length of my list, compkeys. When I make each button, it is given a previously made function which takes one input. I am trying to make the input of the function specific to the iteration of the for loop. For example, the first button that is created in the loop should have the first item in the list comp keys as input in its function.

However, each button is only receiving an input of the final value of x, instead of the value of x depending on how many times the loop has repeated. Thank you for any and all help:)

import tkinter

compkeys = [2017onsc, 2017onwat]

for x in range(len(compKeys)):
    compButton = Button(root, text = compKeys[x], command=lambda: compBuDef(compKeys[x]))
    compButton.place(x=x * 100 + 200, y=300)
Keenan B
  • 37
  • 8

1 Answers1

3

You must pass the parameter through the lambda function:

for x in range(len(compKeys)):
    compButton = Button(root, text=compKeys[x], command=lambda z=compKeys[x]: compBuDef(z))
    compButton.place(x=x*100+200, y=300)

or better, iterating over elements:

for idx, ckey in enumerate(compKeys):
    compButton = Button(root, text=ckey, command=lambda z=ckey: compBuDef(z))
    compButton.place(x=idx*100+200, y=300)
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • Much appreciated. End. – Keenan B Dec 02 '17 at 03:00
  • You are welcome, I am glad I could help, If you feel that my answer helped you, you could consider [what to do when someone answers my question](https://stackoverflow.com/help/someone-answers) [how to accept my answer](http://meta.stackexchange.com/a/5235) – Reblochon Masque Dec 02 '17 at 03:01