Here's some (python 3) code:
from tkinter import *
def makeButtons():
global mainFrame
listy = ["a", "b", "c"]
dicty = {"a":["1", "2", "3"], "b":["4", "5", "6", "7"], "c":["8", "9"]}
buttons = []
for x, item in enumerate(listy):
for y, value in enumerate(dicty[item]):
btn=Button(mainFrame, text=value)
btn.grid(column=x, row=y)
buttons.append(btn)
for i, but in enumerate(buttons):
text = buttons[i]["text"]
but.config(command=lambda *a: vocabMode(i, text))
def vocabMode(i, text):
print(i, text)
root = Tk()
mainFrame = Frame(root)
mainFrame.grid(column=1, row=2)
makeButtons()
root.mainloop()
Go ahead, run it. It works. Except for one small thing.
I'm expecting it to print the text of the label. But no matter what I try, it always prints the value of the last button created. I can't find a solution anywhere when I want it to print its own value. Thanks for the help.
Edit: It has been claimed that this is a duplicate of Generating functions inside loop with lambda expression in python. I'm not sure how. The answers there don't resolve my issues, or if they do, the relationship is too abstract for me to understand.