Python2 Tkinter 按钮网格,每个按钮都有一个命令来改变它的显示文本

Python2 Tkinter Grid of buttons, each with a command to change it's display text

我在 python2 中制作了一个基本的 roguelike,它使用基于二维数组的关卡,如下所示:

map = [
['a','b'],
['c','d']
]

正如您想象的那样,当涉及到大级别(20x20 或 30x30)时,这很乏味,所以我决定在 Tkinter 中创建一个级别编辑器。我的想法是有一个大的按钮网格和一个文本框。您在文本框中输入一个数字,当您单击一个按钮时,该按钮的标签会更改为该数字(每个数字对应关卡中的一个精灵)。很简单。

我的问题是当我创建这个按钮网格时:

for i in range(10):
    for j in range(10):
        Button(
            root,
            text=str(i)+','+str(j),
            command = ???
            ).grid(row=i,column=j)

这肯定会创建一个按钮网格。但是,我不知道将什么作为命令参数。我已经尝试了一些方法,但它们都回到了同一个问题:由于我是通过 for 循环创建每个按钮的,因此它们不能包含在变量中。 比如我不能说:

...
for j in range(10):
    myButton = Button(...)
...

因为每次迭代都会覆盖它。

我花了几个小时试图找到解决这个问题的方法,但找不到。有什么我想念的吗?对不起,如果我没有很好地解释我的问题。
Here's my full code if you need it.

不是像myButton那样分配给变量,而是分配给的字典、列表或其他序列Button class。使用列表:

buttons = []
...
for j in range(10):
    buttons.append(Button(...))

或使用字典:

buttons = {}
for j in range(10):
    buttons[j] = Button(...)

如果我对你的问题的理解正确,一个好的解决方案是将 subclass Button 与一个预先设置了命令的 class ,然后制作一个 2-您的 Button 子 class 的维数组。这样,它几乎可以完全反映您正在创建的结构。所以像这样:

class MyButton(Button):
    def __init__(self, master, **kwargs):
        super().__init__(master, command=lambda: command(), **kwargs)
        # Whatever else you want to set, do it here
    def command(self):
        # You want the button to scroll through letters when you click, 
        # if I understand the question right. You'll have to implement 
        # get_next_letter() yourself. 
        self.text = self.get_next_letter()
# later...

buttons = [[MyButton() for j in range(10)] for i in range(10)]
for i in buttons:
    for j in i: 
        # Set up your grid, etc. here.