Try this:
from functools import partial
import tkinter as tk
import string
def whenPressed(button, text):
print(text)
root = tk.Tk()
alphabet = list(string.ascii_lowercase)
for i in alphabet:
btn = tk.Button(root, text=i)
command = partial(whenPressed, btn, i)
btn.config(command=command)
row = alphabet.index(i) // 13
column = alphabet.index(i) % 13
btn.grid(row=row, column=column, sticky="news")
You have to update the button's command
after you create it using <tkinter.Button>.config(command=...)
. I also used functools.partial
. Its documentation is here. Also it's usually better to also pass in the text instead of having button["text"]
.
A little bit of updated version to avoid calculations to use with rows and columns:
from functools import partial
import tkinter as tk
import string
def whenPressed(button, text):
print(text)
root = tk.Tk()
alphabet = list(string.ascii_lowercase)
for i in range(2):
for j in range(13):
text = alphabet[13*i+j]
btn = tk.Button(root, text=text)
command = partial(whenPressed, btn, text) # Also can use lambda btn=btn,text=text: whenPressed(btn, text)
btn.config(command=command)
btn.grid(row=i, column=j, sticky="news")
root.mainloop()