添加默认配置并优化配置加载逻辑

This commit is contained in:
moyanj 2024-09-09 15:55:45 +08:00
parent 83324f114b
commit 50555786fd
2 changed files with 31 additions and 3 deletions

View File

@ -9,13 +9,16 @@ class Config:
该类通过读取配置文件并将内容映射到实例属性中使得配置项可以像访问普通属性一样被访问
它支持递归加载字典类型的配置项以及直接加载列表和基本数据类型的配置项
"""
base_config = {
"theme": "dark",
}
def __init__(self):
"""
初始化Config实例从配置文件中加载配置并更新实例属性
"""
# 加载配置文件并指定编码为utf-8确保中文字符正确解析
self._conf_Dict = json5.load(os.path.join(env.dirs.user_config_path, "config.json"), encoding="utf-8")
self._conf_Dict = json5.load(open(os.path.join(env.dirs.user_config_path, "config.json"), encoding="utf-8"))
self._conf_Dict = self.merge_dicts(self.base_config, self._conf_Dict)
# 设置实例的名称,用于标识配置类型
self.__name__ = "<Standard Dictionary>"
# 更新实例属性,将配置项映射为可直接访问的属性
@ -41,7 +44,27 @@ class Config:
raise AttributeError(
f"'{self.__class__.__name__}' object has no attribute '{name}'"
)
def merge_dicts(self, *dict_args):
"""
递归合并多个字典
参数:
*dict_args: 多个字典参数按优先级从低到高传递
default (any, 可选): 默认值当找不到键时返回此值默认为 None
返回:
合并后的字典
"""
result = {}
for dictionary in dict_args:
for key, value in dictionary.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
# 如果当前键对应的值都是字典,则递归合并
result[key] = self.merge_dicts(result[key], value)
else:
# 否则直接覆盖或设置值
result[key] = value
return result
def update(self):
"""
更新实例属性将配置字典中的内容映射到实例属性中

View File

@ -16,7 +16,12 @@ class MainWindow(FluentWindow):
# 设置窗口标题
self.setWindowTitle("HoYoCenter")
if env.config.theme == "dark":
setTheme(Theme.DARK)
elif env.config.theme == "light":
setTheme(Theme.LIGHT)
else:
setTheme(Theme.AUTO)
# 定义id和对象映射
self.id2obj = {