Kivy+Python项目引入sqlite3后触发AttributeError问题求助
问题分析与解决方案
问题根源
模块加载顺序冲突
启动流程触发了未完成的模块导入:main.py→ 导入core.screen_manager→ 加载screen_manager.kv→ kv解析器尝试导入core.children→ 此时children.py顶部直接导入数据库模块,导致Children类还未完成定义,core模块也未完成对children子模块的注册,最终kv解析器抛出AttributeError: module 'core' has no attribute 'children'。数据库路径隐藏问题
vaccination_calendar.py中使用相对路径连接数据库,当从项目根目录运行程序时,会在根目录而非application/database/下寻找数据库文件,后续会触发找不到数据库的错误。
解决方案
1. 延迟数据库模块导入
将数据库导入语句移到类方法内部,避免在模块加载阶段打断Children类的定义流程,确保kv解析器能正常获取到模块:
修改children.py:
from kivy.lang import Builder from kivy.uix.screenmanager import Screen from kivymd.uix.list import OneLineAvatarIconListItem, IconLeftWidget Builder.load_file("layouts/children.kv") class Children(Screen): def on_enter(self, *args): # 进入页面时再导入数据库模块并调用方法 from application.database.vaccination_calendar import get_children children_data = get_children() # 后续处理数据(如更新UI) pass
2. 修复数据库连接路径
使用绝对路径连接数据库,避免因运行目录不同导致找不到文件:
修改vaccination_calendar.py:
import sqlite3 import os def get_children(): # 获取数据库文件的绝对路径 db_dir = os.path.dirname(os.path.abspath(__file__)) db_path = os.path.join(db_dir, "vaccination_calendar.db") statement = "select * from children" with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cursor.execute(statement) children_list = [{"id": child[0], "name": child[1], "birth_date": child[2], "days_age": child[3]} for child in cursor.fetchall()] # 查询操作无需commit,仅增删改需要 # conn.commit() # 可删除此行 return children_list
3. 规范Python包结构(可选)
在core目录下创建空的__init__.py文件,让Python将其识别为标准包,避免命名空间导入的潜在问题:
application/core/__init__.py
4. 正确使用动态导入(针对之前的尝试)
如果需要动态导入,确保路径正确:
def load_children_data(): import os import sys # 将项目根目录加入sys.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from application.database.vaccination_calendar import get_children return get_children()
内容的提问来源于stack exchange,提问作者przemek56
相关产品推荐
相关产品推荐

