0

I am using a for loop and a dictionary to create buttons and labels but the command assigned to the button passes the key through. Somehow the key changes to the last iterated key on all of the buttons, therefore not passing the right things to the command. How do I fix this problem?

Example code:

from Tkinter import *
root=Tk()
dic={"hello":"friend", "goodbye":"problem", "please":"fix"}
def command(thing):
    print thing
row=1
for i in dic:
    Label(root, text=i).grid(row=row, column=0)
    Button(root, text="Edit", command=lambda: command(i)).grid(row=row, column=1)
    row+=1
root.mainloop()
Jonah Fleming
  • 1,187
  • 4
  • 19
  • 31
  • Do you want to pass the key or the value of the dict? You might take a look at [`dict.iteritems()`](https://docs.python.org/2/library/stdtypes.html#dict.iteritems) – albert Dec 09 '15 at 21:12
  • Lambda is a bad choice go with partial its better and readable and anyone can understand easly from functools import partial ..... button = Button(root, text="Edit", command=partial(command, i)) button.grid(row=row, column=1) – Achayan Dec 09 '15 at 21:48

0 Answers0