pygame_gui icon indicating copy to clipboard operation
pygame_gui copied to clipboard

Submodules cannot load theme file

Open aaronshenhao opened this issue 2 years ago • 0 comments

Describe the bug The theme file cannot be loaded from submodules using relative paths. create_resource_path() in line 226 of utility.py uses os.path.abspath("."), which returns the path of the main directory, rather than the subdirectory of the submodule.

For example, if we have the following structure (init.py is included in each package, but omitted for clarity):

  • MyProject
    • src
      • main.py
      • submodules
        • submodule.py
        • theme.json
    • tests ....

If we run python main.py, os.path.abspath(".") returns the absolute path the MyProject (/.../MyProject) rather than /.../MyProject/src or /..../MyProject/src/submodules as expected. I was confused, until I got the debugger out.

To Reproduce Steps to reproduce the behaviour:

  1. Generate the project directory as above (with __init__.py files)
  2. Use manager.get_theme().load_theme("theme.json") in submodule.py (you'll have to initialize manager first)
  3. You'll get a warning that Pygame GUI wasn't able to load the theme.

Expected behavior I expected the path to be relative to the module calling it. The docstring in create_resource_path() states that it works with relative paths, but it is unclear what its relative to. In this case, since theme.json is in the same directory as submodule.py, which is loading the theme, it should work.

Platform and software (please complete the following information):

  • OS: Windows
  • Pygame GUI version 0.6.9
  • Pygame version 2.4.0

Comments I'm not sure if this is actually a bug, or the expected behavior. It would be good if the Theme Guide docs could clarify this. In either case, I thought it might be useful to create an issue so others can find it. Loading fonts using manager.add_font_paths() has the same issue.

Edit: To get around it, you can define the following function in the submodule. This returns the relative path to a file in the same folder as submodule. That way you don't have to hard-code the name of the parent directories:

import os
import pathlib
def get_rel_path(self, file_name):
    base_dir = pathlib.Path().resolve()
    cur_dir = pathlib.Path(__file__).parent.resolve()
    rel_dir_path = os.path.relpath(cur_dir, base_dir)
    return os.path.join(rel_dir_path, file_name)

aaronshenhao avatar May 12 '23 03:05 aaronshenhao