Skip to content

Instantly share code, notes, and snippets.

@hdary85
Last active November 24, 2023 04:59
Show Gist options
  • Save hdary85/9e8e6fed2aa4b46010d8087ec3b730c4 to your computer and use it in GitHub Desktop.
Save hdary85/9e8e6fed2aa4b46010d8087ec3b730c4 to your computer and use it in GitHub Desktop.
def populate_tree(tree, item, dictionary):
if isinstance(dictionary, dict):
for key, value in dictionary.items():
if isinstance(value, dict):
sub_item = tree.insert(item, "end", text=key)
populate_tree(tree, sub_item, value)
else:
tree.insert(item, "end", text=key, values=(value,))
else:
tree.insert(item, "end", values=(dictionary,))
def on_double_click(event):
item = tree.focus()
item_text = tree.item(item, "text")
old_value = tree.item(item, "values")[0] if tree.item(item, "values") else ""
entry_popup = tk.Toplevel(root)
entry_popup.title("Edit Value")
entry_label = ttk.Label(entry_popup, text=f"Edit {item_text}:")
entry_label.pack()
entry_var = tk.StringVar(value=old_value)
entry = ttk.Entry(entry_popup, textvariable=entry_var)
entry.pack()
def save_changes():
new_value = entry_var.get()
tree.item(item, values=(new_value,))
update_dictionary(item_text, new_value)
entry_popup.destroy()
save_button = ttk.Button(entry_popup, text="Save", command=save_changes)
save_button.pack()
def update_dictionary(item_text, new_value):
# Update the dictionary based on the edited value
# This function should update the actual dictionary
def find_key(d, key):
for k, v in d.items():
if k == key:
d[k] = new_value
return
if isinstance(v, dict):
find_key(v, key)
find_key(nested_dict, item_text)
def create_gui():
global root
root = tk.Tk()
root.title("Nested Dictionary Editor")
main_frame = ttk.Frame(root)
main_frame.pack(fill=tk.BOTH, expand=True)
global tree
tree = ttk.Treeview(main_frame)
tree["columns"] = ("Value")
tree.column("#0", width=150)
tree.column("Value", width=150)
tree.heading("#0", text="Key")
tree.heading("Value", text="Value")
populate_tree(tree, "", nested_dict)
tree.bind("<Double-1>", on_double_click)
tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
root.mainloop()
if __name__ == "__main__":
create_gui()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment