Make tkinter buttons for every item in a list?
python, python-2.7, tkinter
Solution
There are two things here:
You need to indent the following line one level:
button.pack()
Currently, you only have the `pack` method being called on the last button. Making this change will cause it to be called for each button.
All of the buttons are sending `'item3'` to `func` because that is the current value of `item`. It is important to remember that the expression enclosed by a lambda function is evaluated at run-time, not compile-time.
However, it is also important to remember that both a function's parameters as well as their default values (if any) are evaluated at compile-time, not run-time.
This means that you can fix the problem by giving the lambda a parameter whose default value is set to `item`. Doing so will "capture" the value of `item` for each iteration of the for-loop.
Below is a version of your script that addresses these issues:
from Tkinter import *
root = Tk()
def func(name):
print name
mylist = ['item1', 'item2', 'item3']
for item in mylist:
button = Button(root, text=item, command=lambda x=item: func(x))
button.pack()
root.mainloop()
Problem
I would like to make some buttons, with a list of items I get back from a database, that all call a function passing in the list item. Something like this code but that works. The problem with this code is that all of the buttons call the function with `'item3'`. ``` #!/usr/bin/env python from Tkinter import * root = Tk() def func(name): print name mylist = ['item1','item2','item3'] for item in mylist: button = Button(root,text=item,command=lambda:func(item)) button.pack() root.mainloop() ```