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

蛇游戏替换食物为图片时出现AttributeError问题求助

蛇游戏加载食物图片报错:AttributeError: 'str' object has no attribute '_type'

问题描述

蛇游戏开发接近完成,尝试将食物从圆形替换为实际食物图片时出现报错,相关代码及错误信息如下:

food.py 代码

from turtle import Turtle
from random import randint, choice
from foods import foods, shape_names


class Food(Turtle):
    def __init__(self):
        super().__init__()
        self.shape(choice(shape_names))
        self.penup()
        self.shapesize(stretch_len=0.5, stretch_wid=0.5)
        self.color('blue')
        self.speed(0)
        self.refresh()

    def refresh(self):
        rand_x = randint(-280, 280)
        rand_y = randint(-280, 280)
        self.shape(choice(shape_names))
        self.goto(x=rand_x, y=rand_y)

foods.py 代码

apple = 'food/apple.png'
burger = 'food/burger.png'
cake = 'food/cake.png'
cherries = 'food/cherries.png'
donut = 'food/donut.png'
drumstick = 'food/drumstick.png'
icecream = 'food/icecream.png'
lemon = 'food/lemon.png'
meat = 'food/meat.png'
pizza = 'food/pizza.png'
strawberry = 'food/strawberry.png'
taco = 'food/taco.png'

foods = {'apple': apple, 'burger': burger, 'cake': cake, 'cherries': cherries, 'donut': donut, 'drumstick': drumstick,
         'icecream': icecream, 'lemon': lemon, 'meat': meat, 'pizza': pizza, 'strawberry': strawberry, 'taco': taco}

shape_names = ['apple', 'burger', 'cake', 'cherries', 'donut', 'drumstick', 'icecream', 'lemon', 'meat', 'pizza',
               'strawberry', 'taco']

报错信息

Traceback (most recent call last):
  File "C:\Users\ZSH\PycharmProjects\snake-game\main.py", line 21, in <module>
    food = Food()
  File "C:\Users\ZSH\PycharmProjects\snake-game\food.py", line 9, in __init__
    self.shape('meat')
  File "C:\Users\ZSH\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 2778, in shape
    self.turtle._setshape(name)
  File "C:\Users\ZSH\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 2494, in _setshape
    if self._type == "polygon" == screen._shapes[shapeIndex]._type:
AttributeError: 'str' object has no attribute '_type'

Process finished with exit code 1

解决方案

报错核心原因:turtle无法直接识别自定义的形状名称(如'meat'),必须先将图片注册为可用形状。修改步骤如下:

  1. 导入turtle.Shape类,提前注册所有食物图片,将自定义形状名称与图片路径关联
  2. 移除color设置(图片会覆盖颜色,无需额外设置)
  3. 确保注册完成后再调用shape()方法

修改后的food.py代码:

from turtle import Turtle, register_shape, Shape
from random import randint, choice
from foods import foods, shape_names

# 提前注册所有食物图片,将形状名称与图片绑定
for shape_name, img_path in foods.items():
    food_shape = Shape("image", img_path)
    register_shape(shape_name, food_shape)

class Food(Turtle):
    def __init__(self):
        super().__init__()
        self.penup()
        self.shapesize(stretch_len=0.5, stretch_wid=0.5)
        self.speed(0)
        self.refresh()

    def refresh(self):
        rand_x = randint(-280, 280)
        rand_y = randint(-280, 280)
        chosen_shape = choice(shape_names)
        self.shape(chosen_shape)
        self.goto(x=rand_x, y=rand_y)

注意事项

  • 确保food文件夹存在于项目根目录,所有图片路径正确且文件存在
  • 若出现图片加载失败,可尝试将图片转为GIF格式(部分Python环境对PNG的支持依赖Tkinter版本)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:30:50