<p>这里已经有了一些很好的答案,但我相信这一个符合“简单”的条件(它在tkinter和uuid库中只使用PythonBult)。</p>
<p>它基于John Gaines Jr.在<a href="https://stackoverflow.com/questions/8574070/python-display-a-dict-of-dicts-using-a-ui-tree-for-the-keys-and-any-other-widg">another question</a>中的回答,由Will Ware修改为支持列表,由我修改为也支持元组(在python 3上运行)。</p>
<p>我还重新组织了它,以便您可以用<code>tk_tree_view(data)</code>这样简单的东西调用查看器,并传入一个字典(如最后的示例所示)。</p>
<pre><code>import uuid
import tkinter as tk
from tkinter import ttk
def j_tree(tree, parent, dic):
for key in sorted(dic.keys()):
uid = uuid.uuid4()
if isinstance(dic[key], dict):
tree.insert(parent, 'end', uid, text=key)
j_tree(tree, uid, dic[key])
elif isinstance(dic[key], tuple):
tree.insert(parent, 'end', uid, text=str(key) + '()')
j_tree(tree, uid,
dict([(i, x) for i, x in enumerate(dic[key])]))
elif isinstance(dic[key], list):
tree.insert(parent, 'end', uid, text=str(key) + '[]')
j_tree(tree, uid,
dict([(i, x) for i, x in enumerate(dic[key])]))
else:
value = dic[key]
if isinstance(value, str):
value = value.replace(' ', '_')
tree.insert(parent, 'end', uid, text=key, value=value)
def tk_tree_view(data):
# Setup the root UI
root = tk.Tk()
root.title("tk_tree_view")
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')
j_tree(tree, '', data)
tree.pack(fill=tk.BOTH, expand=1)
# Limit windows minimum dimensions
root.update_idletasks()
root.minsize(root.winfo_reqwidth(), root.winfo_reqheight())
root.mainloop()
if __name__ == "__main__":
# Setup some test data
data = {
"firstName": "John",
"lastName": "Smith",
"gender": "male",
"age": 32,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"},
"phoneNumbers": [
{"type": "home", "number": "212 555-1234"},
{"type": "fax",
"number": "646 555-4567",
"alphabet": [
"abc",
"def",
"ghi"]
}
]}
# call it with
tk_tree_view(data)
</code></pre>
<p>看起来是这样的:</p>
<p><a href="https://i.stack.imgur.com/AwOH9.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/AwOH9.jpg" alt="enter image description here"/></a></p>