CustomTkinter/customtkinter/windows/widgets/theme/theme_manager.py

56 lines
2.1 KiB
Python
Raw Permalink Normal View History

2022-02-23 00:38:40 +03:00
import sys
import os
import pathlib
import json
2022-11-27 14:22:25 +03:00
from typing import List, Union
2022-02-23 00:38:40 +03:00
class ThemeManager:
2022-02-23 00:38:40 +03:00
2022-11-27 14:22:25 +03:00
theme: dict = {} # contains all the theme data
_built_in_themes: List[str] = ["blue", "green", "dark-blue", "sweetkind"]
_currently_loaded_theme: Union[str, None] = None
@classmethod
def load_theme(cls, theme_name_or_path: str):
script_directory = os.path.dirname(os.path.abspath(__file__))
2022-11-27 14:22:25 +03:00
if theme_name_or_path in cls._built_in_themes:
customtkinter_path = pathlib.Path(script_directory).parent.parent.parent
with open(os.path.join(customtkinter_path, "assets", "themes", f"{theme_name_or_path}.json"), "r") as f:
cls.theme = json.load(f)
else:
with open(theme_name_or_path, "r") as f:
cls.theme = json.load(f)
2022-11-27 14:22:25 +03:00
# store theme path for saving
cls._currently_loaded_theme = theme_name_or_path
2022-11-27 04:48:09 +03:00
# filter theme values for platform
for key in cls.theme.keys():
# check if values for key differ on platforms
if "macOS" in cls.theme[key].keys():
if sys.platform == "darwin":
cls.theme[key] = cls.theme[key]["macOS"]
elif sys.platform.startswith("win"):
cls.theme[key] = cls.theme[key]["Windows"]
else:
cls.theme[key] = cls.theme[key]["Linux"]
2022-11-27 14:22:25 +03:00
# fix name inconsistencies
if "CTkCheckbox" in cls.theme.keys():
cls.theme["CTkCheckBox"] = cls.theme.pop("CTkCheckbox")
if "CTkRadiobutton" in cls.theme.keys():
cls.theme["CTkRadioButton"] = cls.theme.pop("CTkRadiobutton")
2022-11-27 14:22:25 +03:00
@classmethod
def save_theme(cls):
if cls._currently_loaded_theme is not None:
if cls._currently_loaded_theme not in cls._built_in_themes:
with open(cls._currently_loaded_theme, "r") as f:
json.dump(cls.theme, f, indent=2)
else:
raise ValueError(f"cannot modify builtin theme '{cls._currently_loaded_theme}'")
else:
raise ValueError(f"cannot save theme, no theme is loaded")