From 318e32276af0a194a6d1641cf86719e3d65cd7f1 Mon Sep 17 00:00:00 2001 From: Hsieh-Fu Tsai Date: Fri, 12 Mar 2021 15:14:57 +0900 Subject: [PATCH] add duplicate item function duplicate item for easily duplicating dict in configuration. duplicated items will disappear the next load. duplicated dicts and lists will show as duplicate number in the first session, but the numbers will be updated in the next load. --- JsonEditor.py | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/JsonEditor.py b/JsonEditor.py index 31dcf4b..7f05816 100644 --- a/JsonEditor.py +++ b/JsonEditor.py @@ -21,7 +21,13 @@ """ +""" +Original author and repo +Abdullah Ahmad Zarir +https://github.com/zargit/tkinter-json-editor + +""" class ValueTypes: DICT = 1 LIST = 2 @@ -56,6 +62,9 @@ def __init__(self, master, **options): self.popup_menu_actions['add_child_filepath'] = {'text': 'Add Filepath', 'action': lambda: self.add_item_from_input(ValueTypes.FILEPATH)} + #add Duplicate here + self.popup_menu_actions['add_duplicate'] = {'text': 'Duplicate', + 'action': lambda: self.duplicate_item_from_input(self.get_selected_index())} self.popup_menu_actions['edit_child'] = {'text': 'Edit', 'action': lambda: self.edit_item_from_input()} @@ -324,6 +333,30 @@ def edit_item_from_input(self): if self.verify_value(value): self.edit_item(selection, value=value) + def duplicate_item_from_input(self, index): + """ + :param index: Duplicate the item at index and its children from the list + + """ + #print("duplicate item from input") + json_root = self.get_json_root(index) + if index == json_root: + for item in self.tree.get_children(index): + key_item = self.get_key(item) + value_item = self.get_value(item) + self.add_item(item, key_item, value_item) + else: + key_index = self.get_key(index) + value_index = self.get_value(index) + parent_index=self.tree.parent(index) + self.add_item(key_index, value_index, parent_index) + + + if self.tree.tag_has(Tags.FILE, json_root): + self.save_json_file(self.get_json_filepath(json_root), self.get_value(json_root)) + + + def remove_item(self, index): """ :param index: Removes the item at index and its children from the list. @@ -337,7 +370,7 @@ def remove_item_from_input(self, index): """ json_root = self.get_json_root(index) - + print(json_root) if index == json_root: for item in self.tree.get_children(index): self.remove_item(item) @@ -392,7 +425,7 @@ def save_json_file(self, filepath, data): :param data: A object. """ with open(filepath, 'w') as f: - json.dump(data, f) + json.dump(data, f, sort_keys=True, indent=4) def get_selected_index(self): """