为什么不显示前两个 WhitePawn() 实例的图像?

Why aren't the images of the first two instances of WhitePawn() displayed?

这是我的代码:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image
from kivy.uix.relativelayout import RelativeLayout


class WhitePawn():
    def __init__(self):
        self.source='whitepawn.png'
        
class CubeWidget(RelativeLayout):
    def __init__(self,color,id,piece,**kwargs):
        self.color=color
        self.id=id
        self.piece=piece
        super().__init__(**kwargs)
        if self.piece:
            self.img=Image(source='whitepawn.png')
            self.add_widget(self.img)
    def on_touch_down(self, touch):
        if self.collide_point(touch.x,touch.y):
            print(self.id,self.pos)
            return True
        return super().on_touch_down(touch)    
class New_Board(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.board=[]
        self.theme=None
        self.gen_board()
    def gen_board(self):
        a=[(WhitePawn(),1,1),(WhitePawn(),2,2),(WhitePawn(),3,3)]
        for i in range(8):
            for j in range(8):
                color=(0,1,0,1) if (i+j)%2!=0 else (1,1,1,1)
                for k in a:
                    if (k[1],k[2])==(i,j):
                        cube=CubeWidget(color,(i,j),k[0])
                        self.board.append((k[0],cube))
                    else:
                        cube=CubeWidget(color,(0,0),None)
                self.add_widget(cube)
class MyChessApp(App):
    def build(self):
        board=New_Board()
        return board
           
MyChessApp().run()

只有最后一个 whitepawn 实例显示图像 none 其他。

你的方法有问题。您的 for k in a: 循环将棋盘的每个方块打印三次。

这是一个简短的可重现示例,说明您当前正在做什么。

a = [(1, 1), (2, 2), (3, 3)]

for i in range(8):
    for j in range(8):
        for k in a:
            if (k[0], k[1]) == (i, j):
                print((i, j), 'printed piece')
            else:
                print((i, j), 'printed blank')

对于职位(1, 1),您将看到:

(1, 1) printed piece
(1, 1) printed blank
(1, 1) printed blank

如您所见,(3, 3) 是唯一一个棋子处于最终检查位置的棋子。这就是为什么它是幸存者。

(3, 3) printed blank
(3, 3) printed blank
(3, 3) printed piece

如果 for 循环没有为片段产生任何结果,一个简单的解决方法是在最后的 for 循环中使用 else 来打印空白位置。

a = [(1, 1), (2, 2), (3, 3)]

for i in range(8):
    for j in range(8):
        for k in a:
            if (k[0], k[1]) == (i, j):
                print((i, j), 'printed piece')
                break
        else:
            print((i, j), 'printed blank')

但是,有些人回避 for 循环中的 else,因为它是语言中使用率较低的部分。

如果您想要在不使用 else 的情况下工作的东西,这应该可以工作。

a = [(1, 1), (2, 2), (3, 3)]

for i in range(8):
    for j in range(8):
        piece = None
        for k in a:
            if (k[0], k[1]) == (i, j):
                piece = k
        if piece is not None:
            print((piece[0], piece[1]), 'printed piece')
        else:
            print((i, j), 'printed blank')