Skip to content

Instantly share code, notes, and snippets.

@lukestanley
Created June 5, 2017 10:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukestanley/8525f9fdcb903a43376a35a77575edff to your computer and use it in GitHub Desktop.
Save lukestanley/8525f9fdcb903a43376a35a77575edff to your computer and use it in GitHub Desktop.
Use Python's built in tk to view Python dict as a tree, with collapsing and such
# Credit to https://stackoverflow.com/a/22722889/122364
import uuid
import tkinter as tk
from tkinter import ttk
def json_tree(tree, parent, dictionary):
for key in dictionary:
uid = uuid.uuid4()
if isinstance(dictionary[key], dict):
tree.insert(parent, 'end', uid, text=key)
json_tree(tree, uid, dictionary[key])
elif isinstance(dictionary[key], list):
tree.insert(parent, 'end', uid, text=key + '[]')
json_tree(tree,
uid,
dict([(i, x) for i, x in enumerate(dictionary[key])]))
else:
value = dictionary[key]
if value is None:
value = 'None'
tree.insert(parent, 'end', uid, text=key, value=value)
def show_data(data):
# Setup the root UI
root = tk.Tk()
root.title("JSON viewer")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
# Setup the Frames
tree_frame = ttk.Frame(root, padding="3")
tree_frame.grid(row=0, column=0, sticky=tk.NSEW)
# Setup the Tree
tree = ttk.Treeview(tree_frame, columns='Values')
tree.column('Values', width=100, anchor='center')
tree.heading('Values', text='Values')
json_tree(tree, '', data)
tree.pack(fill=tk.BOTH, expand=1)
# Limit windows minimum dimensions
root.update_idletasks()
root.minsize(800, 800)
root.mainloop()
@michaelotty
Copy link

Line 17 equivalent to dict(enumerate(dictionary[key])) since there is no need for list comprehension.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment