theme_manager.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import sys
  2. import os
  3. import pathlib
  4. import json
  5. from typing import List, Union
  6. class ThemeManager:
  7. theme: dict = {} # contains all the theme data
  8. _built_in_themes: List[str] = ["blue", "green", "dark-blue", "sweetkind"]
  9. _currently_loaded_theme: Union[str, None] = None
  10. @classmethod
  11. def load_theme(cls, theme_name_or_path: str):
  12. script_directory = os.path.dirname(os.path.abspath(__file__))
  13. if theme_name_or_path in cls._built_in_themes:
  14. customtkinter_path = pathlib.Path(script_directory).parent.parent.parent
  15. with open(os.path.join(customtkinter_path, "assets", "themes", f"{theme_name_or_path}.json"), "r") as f:
  16. cls.theme = json.load(f)
  17. else:
  18. with open(theme_name_or_path, "r") as f:
  19. cls.theme = json.load(f)
  20. # store theme path for saving
  21. cls._currently_loaded_theme = theme_name_or_path
  22. # filter theme values for platform
  23. for key in cls.theme.keys():
  24. # check if values for key differ on platforms
  25. if "macOS" in cls.theme[key].keys():
  26. if sys.platform == "darwin":
  27. cls.theme[key] = cls.theme[key]["macOS"]
  28. elif sys.platform.startswith("win"):
  29. cls.theme[key] = cls.theme[key]["Windows"]
  30. else:
  31. cls.theme[key] = cls.theme[key]["Linux"]
  32. # fix name inconsistencies
  33. if "CTkCheckbox" in cls.theme.keys():
  34. cls.theme["CTkCheckBox"] = cls.theme.pop("CTkCheckbox")
  35. if "CTkRadiobutton" in cls.theme.keys():
  36. cls.theme["CTkRadioButton"] = cls.theme.pop("CTkRadiobutton")
  37. @classmethod
  38. def save_theme(cls):
  39. if cls._currently_loaded_theme is not None:
  40. if cls._currently_loaded_theme not in cls._built_in_themes:
  41. with open(cls._currently_loaded_theme, "r") as f:
  42. json.dump(cls.theme, f, indent=2)
  43. else:
  44. raise ValueError(f"cannot modify builtin theme '{cls._currently_loaded_theme}'")
  45. else:
  46. raise ValueError(f"cannot save theme, no theme is loaded")