如何从tkinter中按下的按钮获取网格信息?

如何从tkinter中按下的按钮获取网格信息?

问题描述:

我需要在Python 2.7中使用Tkinter创建按钮表,该表具有 n 行和 n 列,并且在右下角没有按钮.

I need to create table of buttons using Tkinter in Python 2.7, which has n rows and n columns, and has no button in bottom right corner.

问题是,当我按一个按钮时,需要创建可用空间并将该按钮移动到之前为空的空间,而我不能这样做,因为我不知道如何获取网格(x和y轴)的信息以使用它来创建可用空间.

Problem is that when I press a button, in its place, I need to create free space and move that button to space that was empty before, and I cannot do that because I don't know how to get grid (x and y axes) information of pressed button to use it to create free space.

这是我当前的代码:

from Tkinter import *

#Input:
n=int(raw_input("Input whole positive number: "))
L = range(1,n+1)
k = n
m = n

#Program:
root = Tk()
for i in L:
    for j in L:
        frame = Frame(root)
        frame.grid(row = i, column = j)
        if j == k and i == m:
            pass
        else:
            button = Button(frame)
            button.grid(row = i, column = j)


root.mainloop()

就像这样,我想获取按钮网格的位置,并使用它来更改 k m 变量以在按下的位置留出空白按钮是.

It would be something like this, where I wanted to get button grid position, and use it to change k and m variables to make empty space in position where pressed button was.

您可以通过对按钮使用lambda表达式来传递行和列:

You can pass the row and column by using a lambda expression for the button:

button = Button(..., command=lambda row=i, column=j: doSomething(row, column))