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

Python导入错误:无法从tiles.py导入Tile类的原因排查

导入Tile类触发ImportError的问题解决

问题现象

从tiles.py向main.py导入Tile类时出现如下错误:

Traceback (most recent call last):
 File "c:\Users\shireen\Desktop\Clear Code\main.py", line 3, in <module>
 from tiles import Tile
 ImportError: cannot import name 'Tile' from 'tiles' 
 (c:\Users\shireen\Desktop\ClearCode\tiles.py)

涉及代码

main.py

import pygame, sys
from settings import *
from tiles import Tile

# Pygame初始化
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
test_tile = pygame.sprite.Group(Tile((100, 100), 200))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill('black')
    test_tile.draw(screen)

    pygame.display.update()
    clock.tick(60)

tiles.py

import pygame

class Tile(pygame.sprite.Sprite):
    def __init__(self,pos,size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('grey')
        self.rect = self.image.get_rect(topleft = pos)

解决方法

  1. 修正路径名称不一致问题:报错显示main.py所在文件夹是Clear Code(含空格),但系统查找tiles.py时指向的是ClearCode(无空格),这是核心原因。
  2. 统一文件夹命名:将项目所在文件夹名称改为完全一致的形式(要么都用Clear Code,要么都用ClearCode),确保两个文件处于同一目录下。
  3. 重新运行验证:修改完成后启动main.py,确认导入错误消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:13:12