Edit: I think I like @DonQuestion's event-based approach better because it does not require a different function for each button.
Below I've adapted my original code to use
master.bind("<Button-1>", self.onclick)
to react to mouse clicks (instead of using tk.Button(command = ...)
import Tkinter as tk
class ButtonEventBlock(object):
# http://stackoverflow.com/a/6102759/190597
def __init__(self, master, names, cols):
self.names = names
self.cols = cols
self.button = []
for i, name in enumerate(names):
self.button.append(tk.Button(master, text = name))
row, col = divmod(i, self.cols)
self.button[i].grid(sticky = tk.W+tk.E+tk.N+tk.S,
row = row, column = col, padx = 1, pady = 1)
master.bind("<Button-1>", self.onclick)
def onclick(self, event):
info = event.widget.grid_info()
# print(info)
# {'rowspan': '1', 'column': '3', 'sticky': 'nesw', 'ipady': '0', 'ipadx':
# '0', 'columnspan': '1', 'in': <Tkinter.Tk instance at 0xab3d7ec>,
# 'pady': '1', 'padx': '1', 'row': '0'}
row, col = [int(info[key]) for key in ['row', 'column']]
i = self.cols*row + col
print(row, col, self.names[i])
names = ('One', 'Two', 'Three', 'Four', 'Five',
'Six', 'Seven', 'Eight', 'Nine', 'Ten')
root = tk.Tk()
ButtonEventBlock(root, names, cols = 5)
root.mainloop()
