You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy开发中前两个WhitePawn实例的图片为何无法正常显示

问题原因
  • 核心错误为棋盘生成逻辑的变量覆盖问题:你对每个棋盘坐标(i,j)都全量遍历棋子列表a,每次遍历都会重新为cube赋值。当坐标匹配前两个白兵时,生成的带棋子控件会被后续遍历不匹配时生成的无棋子控件覆盖,最终添加到布局的只有遍历完a列表后最后一次赋值的cube。仅a列表最后一个白兵对应的坐标,匹配发生在遍历的最后一步不会被覆盖,因此只有它能正常显示。
  • 次要隐患:id是Kivy控件的内置保留属性,你直接对self.id自定义赋值可能触发未知异常,建议替换为自定义属性名例如grid_pos。
修复后的完整代码
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,grid_pos,piece,**kwargs):
        self.color=color
        self.grid_pos=grid_pos
        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.grid_pos,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)]
        # 提前构建坐标-棋子映射表,避免重复遍历
        pos_piece = {(item[1],item[2]):item[0] for item in a}
        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)
                current_piece = pos_piece.get((i,j), None)
                cube=CubeWidget(color,(i,j),current_piece)
                if current_piece:
                    self.board.append((current_piece,cube))
                self.add_widget(cube)
class MyChessApp(App):
    def build(self):
        board=New_Board()
        return board
           
MyChessApp().run()

内容的提问来源于stack exchange,提问作者Red

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:24:06