In the case where $k$ is algebraically closed and $V$ is finite dimensional: let $\lambda$ be an eigenvalue of $A$ and let $V_\lambda$ be the associated eigenspace and let $W_\lambda=\bigoplus_{\mu\neq\lambda}V_\mu$ be the direct sum of all the other eigenspaces of $A$. Since $A$ is diagonalizable, $V=V_\lambda\oplus W_\lambda$. Let $p_\lambda$ be the projection onto $V_\lambda$ along $W_\lambda$. Clearly, $p_\lambda$ and $A$ commute. From your hypothesis, $p_\lambda\circ B=B\circ p_\lambda$ and hence $B(V_\lambda)\subset V_\lambda$. Denote by $B_\lambda$ the endomorphism of $V_\lambda$ obtained by the restriction of $B$ to $V_\lambda$. Let $C_\lambda$ be an endomorphism of $V_\lambda$, and extend it to an endomorphism of $V$ by adding $W_\lambda$ to its kernel. Then $C$ and $A$ commute, hence $B_\lambda$ and $C_\lambda$ commute. It is a standard fact that the only endomorphism that commutes with all endomorphisms is a multiple of the identity, hence $B_\lambda$ is a multiple of the identity of $V_\lambda$, say $B_\lambda=\mu(\lambda)\,\mathrm{id}_{V_\lambda}$. Now let $P$ be any polynomial that extends $\mu$ (such a polynomial exists, e.g., using Lagrange interpolation polynomials—this is where I use the fact that $V$ is finite-dimensional). We clearly have $P(A)=B$.