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?