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

Python报错:'tuple'对象没有'append'属性,寻求技术解决方案

代码错误求助与修复

我的代码一直出现相同错误,试过各种方法都修不好,求帮忙看看。代码如下:

def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = GameState()
    LoadImages()
    running= True
    sqselected = ()
    playerClicks = ()
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()
                col = location[0]//SQSIZE
                row = location[1]//SQSIZE
                if sqselected == (row,col):
                    sqselected = ()
                    playerClicks = []
                else:
                    sqselected= (row, col)
                    playerClicks.append(sqselected)
                if len(playerClicks)==2:
                    move = Move(playerClicks[0], playerClicks[1], gs.board)
                    print(Move.getChessNotation())
                    gs.Makemove(move)
                    sqselected = ()
                    playerClicks = []

问题排查与修复

  • playerClicks初始化错误:你把playerClicks初始化为元组(),但元组是不可变类型,后续调用append方法会触发AttributeError。需改为列表初始化:playerClicks = []
  • 走法记法调用错误:print(Move.getChessNotation())是调用类的静态方法,但走法记法属于具体的move实例,应改为print(move.getChessNotation())
  • 额外注意点:确保WIDTH、HEIGHT、SQSIZE等常量已定义,p是导入的pygame(需添加import pygame as p),GameState、Move类及LoadImages函数已正确实现,否则会出现未定义相关错误

修复后的代码片段:

def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = GameState()
    LoadImages()
    running= True
    sqselected = ()
    playerClicks = []  # 修复:改为列表类型
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()
                col = location[0]//SQSIZE
                row = location[1]//SQSIZE
                if sqselected == (row,col):
                    sqselected = ()
                    playerClicks = []
                else:
                    sqselected= (row, col)
                    playerClicks.append(sqselected)
                if len(playerClicks)==2:
                    move = Move(playerClicks[0], playerClicks[1], gs.board)
                    print(move.getChessNotation())  # 修复:调用实例方法
                    gs.Makemove(move)
                    sqselected = ()
                    playerClicks = []

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:40:33