Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

python - tkinter - add data from nested list with dictionary to treeview

I am trying to put some data in my treeview and I'm new to the treeview and do'sent understand it fully, if tried to read the documentation, but got even more confused.

I created a nested list with 2 sublists and last some dictionaries.

isolering = [
[
{"name": "mineraluld"},
{"dim": "0,195"},
{"lambda": "0,37"},
{"z": "250"},
{"fire": "NA"}
],
[
{"name": "mineraluld2"},
{"dim": "0,195"},
{"lambda": "0,37"},
{"z": "250"},
{"fire": "NA"}
]]

materialLibrary = [isolering]

Now i can't figure out the proper way to put my data in the treeview.

This is how far I got. I can't figure out, the way to call my data. I trying to it, like you would call it by it's index. But I understand it's wrong.

tree.insert("" , 0, text="Name")
tree.insert("", 1, "dirIso", text="Isolering")
tree.insert("dirIso", 1, text=materialLibrary[0][1][0]["name"],values=(materialLibrary[0][1][0]["dim"],
                                                                     materialLibrary[0][1][0]["lambda"],
                                                                     materialLibrary[0][1][0]["z"],
                                                                     materialLibrary[0][1][0]["fire"]))

I have here a picture of hat I'm trying to accomplish.

enter image description here

The error message I receive is this: KeyError: 'dim'

Any help is appreciated or point in the right direction.

Thx

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Question: add data from nested list with dictionary to treeview

# Set 'text' to the first column heading
tree.heading('#0', text='Name')

# Insert Tree Heading as Item 'dirIso'
# Set 'text' to "Isolering"
tree.insert("", 1, "dirIso", text="Isolering")

# Loop first list
for n, dirIso in enumerate(isolering,1):
    # Make a list of values from the list of Dictionaries
    list_of_column_values = 
        [list(_dict.values())[0] for _dict in dirIso]

    # Insert the list of values
    # First value goes to Treeview 'text'
    # All other values into the following Columns
    tree.insert('dirIso', n, text=list_of_column_values[0], 
                             values=list_of_column_values[1:])

Tested with Python: 3.5


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...