1

I am attempting to streamline the way I produce GUIs. I like the idea of the visual elements of a GUI being held in a data file such as a JSON file and then being interpreted by Python to setup the UI.

This is the JSON file defining the UI layout:

{
    "main screen": {
        "target file button" : {
            "type" : "Button",
            "init" : {
                "text": "Choose Target File"
            },
            "grid" : {
                "row" : 0,
                "column": 0,
                "columnspan": 2
            }
        },
        "delete button" : {
            "type" : "Button",
            "init" : {
                "text": "Delete"
            },
            "grid" : {
                "row" : 1,
                "column": 0
            }
        }
    }
}

And this is the code that uses it:

import tkinter
import json


class UserInterface(tkinter.Tk):

    def __init__(self, layout_path):
        super().__init__()
        self.layout = self.dict_from_jsonfile(layout_path)
        self.init_widgets()


    def init_widgets(self):
        self.widgets = {}
        for key, value in self.layout['main'].items():
            self.widgets[key] = tkinter.__dict__[value['type']](master=self, **value['init'])
            self.widgets[key].grid(**value['grid'])


    def dict_from_jsonfile(self, path, **kwargs):
        with open(path, 'r') as f:
            data = json.load(f, **kwargs)
        return data



if __name__ == '__main__':
    UserInterface("./ui_layout.json").mainloop()

Notice that I am using the tkinter.__dict__ attribute to translate the JSON strings into tkinter objects.

However, this reference in the Python documentation says that using the __dict__ attribute is a problem saying:

"using [__dict__] violates the abstraction of namespace implementation"

What does this mean? How can I implement this so the above idea is not violated?

  • Unrelated to our question, are you aware of [is-there-a-gui-design-app-for-the-tkinter](https://stackoverflow.com/questions/14142194) – stovfl Mar 17 '20 at 20:41
  • Thank you for pointing me to this. I am always looking at different frameworks to glean different benefits based on the app I am trying to write. For my purposes however, I am trying to develop a framework for myself that streamlines and automates many parts of what I do. – FlyTheReddFlagg Mar 18 '20 at 01:26
  • You can try replacing `tkinter.__dict__[...](...)` to `tkinter.Widget(self, value['type'].lower(), value['init'])`. – acw1668 Mar 18 '20 at 15:42
  • Hey that works great! This avoids the issue altogether. (Although I still don't know why `__dict__` is a problem.) – FlyTheReddFlagg Mar 18 '20 at 18:38

0 Answers0