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)
解决方法
- 修正路径名称不一致问题:报错显示
main.py所在文件夹是Clear Code(含空格),但系统查找tiles.py时指向的是ClearCode(无空格),这是核心原因。 - 统一文件夹命名:将项目所在文件夹名称改为完全一致的形式(要么都用
Clear Code,要么都用ClearCode),确保两个文件处于同一目录下。 - 重新运行验证:修改完成后启动
main.py,确认导入错误消失。
内容的提问来源于stack exchange,提问作者user18851688
相关产品推荐
相关产品推荐

