1

I'm just getting started with tkinter and have run into a slight problem:

I'm trying to make tkinter buttons in a dictionary created by a loop. This loop is to automate button creation. Here is an example of what gives me the result that I want (without the loop):

from tkinter import *

letters = ['a','b','c']

root = Tk()

buttons = {}

buttons['a'] = Button(root, text = 'a', command = lambda: print('a'))
buttons['b'] = Button(root, text = 'b', command = lambda: print('b'))
buttons['c'] = Button(root, text = 'c', command = lambda: print('c'))

buttons['a'].pack()
buttons['b'].pack()
buttons['c'].pack()

root.mainloop()

So whenever I click on a button it prints its name.

Now I try to automate this with a 'for' loop as such:

from tkinter import *

letters = ['a','b','c']

root = Tk()

buttons = {}
for u in letters:
    buttons[u] = Button(root, text = u, command = lambda: print(u))
    buttons[u].pack()

root.mainloop()

But it DOESN'T WORK! It just prints 'c' every time, and I don't understand why. I'm guessing it has something to do with the 'lambda' function but I'm lost.

Thanks for your help!

0 Answers0