编辑:我认为我更喜欢@DonQuestion 的基于事件的方法,因为它不需要为每个按钮提供不同的功能。
下面我调整了我的原始代码以使用
master.bind("<Button-1>", self.onclick)
对鼠标点击做出反应(而不是使用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()