From ed83f313ec9bc6f9d408876a25d01afc450f6268 Mon Sep 17 00:00:00 2001 From: yyx <20328610@qq.com> Date: Sun, 28 Sep 2025 20:49:11 +0800 Subject: [PATCH] =?UTF-8?q?PyInstaller=20=E6=89=93=E5=8C=85=E9=80=82?= =?UTF-8?q?=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.py | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/main.py b/src/main.py index 50808cd..2e639d1 100644 --- a/src/main.py +++ b/src/main.py @@ -16,17 +16,36 @@ from typing import List, Set import sys # 导入 sys 模块以支持程序退出 # 本地应用模块导入 -from .questions import ( - HighQuestionGenerator, - MiddleQuestionGenerator, - PrimaryQuestionGenerator, -) +try: + # 尝试直接导入 (适用于 PyInstaller 打包后的可执行文件) + from questions import ( + HighQuestionGenerator, + MiddleQuestionGenerator, + PrimaryQuestionGenerator, + ) +except ImportError: + # 如果失败,则使用相对导入 (适用于用 'python -m' 运行源代码) + from .questions import ( + HighQuestionGenerator, + MiddleQuestionGenerator, + PrimaryQuestionGenerator, + ) # ------------------------------ # 数据库管理 # ------------------------------ -DB_NAME = "accounts.db" +# 动态确定数据库文件的路径 +# 当程序被 PyInstaller 打包时,sys.frozen 属性为 True +if getattr(sys, 'frozen', False): + # 查找可执行文件所在的目录,并在该目录下寻找 accounts.db + # 这让程序能够动态地使用与它放在一起的数据库文件 + executable_dir = os.path.dirname(os.path.abspath(sys.executable)) + DB_NAME = os.path.join(executable_dir, 'accounts.db') +else: + # 在非打包(开发)环境中,使用相对路径 + DB_NAME = os.path.join("src", "accounts.db") + VALID_LEVELS = ["小学", "初中", "高中"] # 将难度级别与对应的生成器类进行映射 @@ -203,7 +222,7 @@ def login_prompt() -> (str, str): # 新增的退出选项 if raw == "-2": - print("已退出。") + print("程序已退出。") sys.exit(0) parts = raw.split() @@ -271,5 +290,4 @@ def main() -> None: except KeyboardInterrupt: print("\n程序已被用户中断,退出。") - main() \ No newline at end of file -- 2.34.1