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

时间:2015-11-30 04:07:31

标签: python python-2.7 tkinter iteration

我在python2中创建了一个基本的roguelike,它使用基于2d数组的级别,如下所示:

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.

2 个答案:

答案 0 :(得分:0)

不是像<{1}}那样分配给变量,而是分配给 myButton类的字典,列表或其他序列。使用列表:

Button

或使用dict:

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

答案 1 :(得分:0)

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

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.