射击游戏开发中TypeError: 'type' object is not subscriptable错误的解决方法咨询
解决TypeError: 'type' object is not subscriptable错误
问题根源
嘿,我一眼就找到问题所在了——你创建ItemBox实例的方式用错符号啦!
在Python里,方括号[]是用来做下标访问的(比如取字典的键值、列表元素),而类本身属于type类型的对象,它不支持下标操作。要创建类的实例,你得用**圆括号()**来调用类的构造函数__init__才行,这就是你触发这个错误的核心原因。
具体修改步骤
你只需要把创建ItemBox实例的代码里的方括号全部改成圆括号就可以解决问题:
错误代码片段:
item_box = ItemBox["health", 100, 300] item_box_group.add(item_box) item_box = ItemBox["ammo", 400, 300] item_box_group.add(item_box) item_box = ItemBox["grenade", 500, 300] item_box_group.add(item_box)
修正后的代码片段:
item_box = ItemBox("health", 100, 300) item_box_group.add(item_box) item_box = ItemBox("ammo", 400, 300) item_box_group.add(item_box) item_box = ItemBox("grenade", 500, 300) item_box_group.add(item_box)
完整修正后的代码参考
为了方便你直接使用,这里贴出所有相关的修正后代码(顺便补充了必要的初始化检查):
import pygame # 假设你已经定义了TILE_SIZE常量 TILE_SIZE = 64 grenade_img = pygame.image.load("img/icons/grenade.png").convert_alpha() # 拾取箱子资源 health_box_img = pygame.image.load("img/icons/health_box.png").convert_alpha() ammo_box_img = pygame.image.load("img/icons/ammo_box.png").convert_alpha() grenade_box_img = pygame.image.load("img/icons/grenade_box.png").convert_alpha() item_boxes = { "health": health_box_img, "ammo": ammo_box_img, "grenade": grenade_img, } class ItemBox(pygame.sprite.Sprite): def __init__(self, item_type, x, y): pygame.sprite.Sprite.__init__(self) self.item_type = item_type self.image = item_boxes[self.item_type] self.rect = self.image.get_rect() self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height())) # 务必先初始化精灵组 item_box_group = pygame.sprite.Group() # 创建物品箱子(已修正实例创建方式) item_box = ItemBox("health", 100, 300) item_box_group.add(item_box) item_box = ItemBox("ammo", 400, 300) item_box_group.add(item_box) item_box = ItemBox("grenade", 500, 300) item_box_group.add(item_box)
额外小提示
记得确认item_box_group已经正确初始化为pygame.sprite.Group(),不然添加实例时会触发新的报错哦。
内容的提问来源于stack exchange,提问作者Kenny Okoye
相关产品推荐
相关产品推荐

