Python Forum
[Tkinter] How to insert data json to treeview tkinter?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] How to insert data json to treeview tkinter?
#1
Hi, I'm using python for a short time and I'm getting a little complicated. What I'm looking for is that when I enter the corresponding tab, it displays the data loaded in a json, through the treeview.

I tried adding the json in this way, but it only lists the first object in the list.

f = open('personal.json',)
    data = json.load(f)


    count=0
    for record in data:
        json_tree.insert(parent='', index="end", iid=count, text="", values=(record[0], record[1],record[2],record[3],record[4],record[5],record[6],record[7]))
        count+=1
[Image: Captura-de-pantalla-2023-01-17-161954.png]

This is how my json looks.

[Image: Captura-de-pantalla-2023-01-17-162419.png]

If I try this way, that I saw in another code, nothing appears in the treeview.

def insert_data():
        with open('personal.json', 'r') as read:
                wList = json.loads(read.read())['Clientes']
                wDict = {}
                wDict['Clientes'] = wList
        
        for weapon in wList:
                json_tree.insert(parent='', index='end', iid=0, text="", values=(weapon['Logo'],weapon['Nombre'],weapon['Tenant ID'],weapon['Aplication ID'],weapon['Secret ID'],weapon['Token'],weapon['Periocididad'],weapon['Token']))
I would be very grateful if someone can exemplify or guide me on what I am doing wrong. Thanks
Reply
#2
I created a simple json file with the data you provided (improvised on 'Logo')
import json

with open('personal.json') as fp:
    data = json.load(fp)

for element in data:
    for key, value in element.items():
        print(f"{key}: {value}")
Output:
Logo: C:/users/*/Desktop/Tkinter/Logos/... Nombre: hola Tennant ID: 1 Application ID: 2 Secret ID: 3 Token: 4 Periocididad: 5 Region: SA
Reply
#3
Hello, thank you for your answer.

If I put the following code, I can see the data I need in the terminal, but I don't know how to pass it with the treeview.insert() to my treeview table.

import json

with open('personal.json') as fp:
        data = json.load(fp)
 
for element in data['Clientes']:
     print(element)
[Image: Captura-de-pantalla-2023-01-17-234606.png]

Now, if I put it the way you showed me, it tells me the following.

Error:
AttributeError: 'str' object has no attribute 'items'
Reply
#4
You load() a jason file. You do not read it.
Reply
#5
You are right, I tried it this way and it worked. Now I can see the data in the table.

f = open ('personal.json', "r")
    data = json.loads(f.read())

    count=0
    for record in data['Clientes']:
        json_tree.insert(parent='', index="end", iid=count, text="", values=(record['Logo'],record['Nombre'],record['Tenant ID'],record['Aplication ID'],record['Secret ID'],record['Token'],record['Periocididad'],record['Region']))
        count+=1
[Image: Captura-de-pantalla-2023-01-18-124705.png]
Reply
#6
Use json.load, not json.loads
json_tree_columns = ('Logo', 'Nombre', 'Tenant ID', 'Secret ID', 'Token', 'Periocididad', 'Region')
with open('personal.json', 'r') as file:  # <- Originally was missing colon
    data = json.load(file)

for count, record in enumerate(data['Clientes'], start=1):
        json_tree.insert(parent='', index="end", iid=count, text="", values=[record[col] for col in json_tree_columns])
Reply
#7
does not work with load, it says

Error:
AttributeError: 'str' object has no attribute 'read'
with loads it shows me the json data in the treeview.

Now I have another question, I have some entries to be able to modify the data obtained from the treeview. These work and when I modify them in the tree they are updated, but how would I call the json in this situation to update the values and not to add them as another object in the list?

with this I select the object in the tree

    def select_record():
        logo_lb.delete(0,END) 
        nombre_lb.delete(0,END)
        tenantid_lb.delete(0,END)
        aplicationid_lb.delete(0,END)
        secretid_lb.delete(0,END)
        token_lb.delete(0,END)
        periodicidad_lb.delete(0,END)
        region_combobox2.delete(0,END)

        selected = json_tree.focus() e
        values = json_tree.item(selected,'values') 
        
        logo_lb.insert(0, values[0]) 
        nombre_lb.insert(0,values[1])
        tenantid_lb.insert(0,values[2])
        aplicationid_lb.insert(0,values[3])
        secretid_lb.insert(0,values[4])
        token_lb.insert(0,values[5])
        periodicidad_lb.insert(0,values[6])
        region_combobox2.insert(0,values[7])
with this I save the updates, which are only visualized in the tree but as it is not connected with the json, the changes are not made in the file.

 def update_record():
     selected = json_tree.focus()      
     json_tree.item(selected, text='', values=(logo_lb.get(),nombre_lb.get(),tenantid_lb.get(),aplicationid_lb.get(),secretid_lb.get(),token_lb.get(),periodicidad_lb.get(),region_combobox2.get())) 

        logo_lb.delete(0,END) 
        nombre_lb.delete(0,END)
        tenantid_lb.delete(0,END)
        aplicationid_lb.delete(0,END)
        secretid_lb.delete(0,END)
        token_lb.delete(0,END)
        periodicidad_lb.delete(0,END)
        region_combobox2.delete(0,END)
[Image: Captura-de-pantalla-2023-01-18-160741.png]
Reply
#8
In your earlier post you said this worked:
f = open ('personal.json', "r")
data = json.loads(f.read())
This code reads the entire file and returns a str object. Then it loads() the str object to create python objects. That works, but why read the file and then convert when you can do it with one call.
python]f = open ('personal.json', "r")
data = json.load(f)
[/python]
The json.load() call reads the dictionary and creates python objects. No need to call read() to get the file contents.

In addition to using json.load(file_obj) instead of json.loads(str_obj), my example used a context manager to automatically close the json file when we were done using it. Your program never closed the file. Leaving files open is a bad practice, and using a context manager makes it really easy to make sure you always close files.
with open('personal.json', 'r') as file:   # opens the file for reading
    data = json.load(file)  # reads the json file and returns python obects
# Automatically closes the file when you exit the code block (de-indent)
Quote:Now I have another question, I have some entries to be able to modify the data obtained from the treeview. These work and when I modify them in the tree they are updated, but how would I call the json in this situation to update the values and not to add them as another object in the list?
You use json.dump(python_object) to write a json file. You cannot dump() a TreeView, so you'll need to collect the TreeView items in Python object that can be dumped. Using something that has the same structure as the object returned by json.load() would be a good idea. Maybe you can use the same object?
Reply
#9
Nice, now I understand the difference and I was able to apply it.

Quote:You use json.dump(python_object) to write a json file. You cannot dump() a TreeView, so you'll need to collect the TreeView items in Python object that can be dumped. Using something that has the same structure as the object returned by json.load() would be a good idea. Maybe you can use the same object?

I tried this way. Me selecciona el item, me lo modifica en el treeview pero en el json me borra lo previo.

selected = json_tree.focus()
    data = json_tree.item(selected, text='', values=(str(logo_lb.get()),str(name_lb.get()),str(lastname_lb.get()),str(something_lb.get())))
with open('prueba1.json', 'w') as f:
        json.dump({'Example': data}, f, indent=4)
I leave an example code.

import json
from tkinter import ttk
from tkinter import *
import tkinter as tk

ventana = tk.Tk()
ventana.title("Test")
ventana.geometry("1000x600")

frame1 = tk.Frame(ventana, bg="green", height=300, width=700)
frame1.grid(row=1, column=0)

frame2 = tk.Frame(ventana, bg="yellow", height=300, width=700)
frame2.grid(row=2, column=0)

frame_entry = tk.Frame(frame2) #Frame para los entry
frame_entry.pack(pady=20)

tree_frame = tk.Frame(frame1) #Frame para el arbol
tree_frame.pack(pady=20)

#style del tree
style = ttk.Style()
style.theme_use("clam")
style.configure("Treeview", background="#c7c7c7", foreground="black", rowheight=25,fieldbackground="#a1a1a1")
style.map("Treeview", background=[('selected','green')])

tree_scroll = Scrollbar(tree_frame) #Frame para el scrollbar del arbol
tree_scroll.pack(side=RIGHT, fill=Y)
#Lista Treeview
json_tree = ttk.Treeview(tree_frame, yscrollcommand=tree_scroll.set)
json_tree.pack()

#config scroll
tree_scroll.config(command=json_tree.yview)

#column
json_tree['column'] = ("Logo", "Name", "Last Name", "Something")

#column
json_tree.column("#0", width=0, minwidth=0)#Columna Fantasma
json_tree.column("Logo", anchor="w", width=120)
json_tree.column("Name", anchor="w", width=120)
json_tree.column("Last Name", anchor="w", width=120)
json_tree.column("Something", anchor="w", width=120)

#headings
json_tree.heading("#0", text="", anchor="w")#Columna Fantasma
json_tree.heading("Logo", text="Logo", anchor="w")
json_tree.heading("Name", text="Name", anchor="w")
json_tree.heading("Last Name", text="Last Name", anchor="w")
json_tree.heading("Something", text="Something", anchor="w")

#color rows
json_tree.tag_configure('par', background="#fff")
json_tree.tag_configure('inpar', background="#d6d6d6")

with open('prueba1.json', "r") as f:
    data = json.load(f)


    count=0
    for record in data['Example']:
        if count % 2 ==0:
            json_tree.insert(parent='', index="end", iid=count, text="", values=(record['Logo'],record['Name'],record['Last Name'],record['Something']), tags=('par',))
        else:    
            json_tree.insert(parent='', index="end", iid=count, text="", values=(record['Logo'],record['Name'],record['Last Name'],record['Something']), tags=('inpar',))

        count+=1


#entrys
l1 = Label( frame_entry, text="Logo")
l1.grid(row=0, column=0)
logo_lb = Entry( frame_entry)
logo_lb.grid(row=1, column=0)

l2 = Label( frame_entry, text="Name")
l2.grid(row=0, column=1)
name_lb = Entry(frame_entry)
name_lb.grid(row=1, column=1)

l3 = Label( frame_entry, text="Last Name")
l3.grid(row=0, column=2)
lastname_lb = Entry(frame_entry)
lastname_lb.grid(row=1, column=2)

l4 = Label( frame_entry, text="Something")
l4.grid(row=0, column=3,)
something_lb = Entry(frame_entry)
something_lb.grid(row=1, column=3)


def select_record():
    #Limpiar las cajas
    logo_lb.delete(0,END) 
    name_lb.delete(0,END)
    lastname_lb.delete(0,END)
    something_lb.delete(0,END)

    selected = json_tree.focus() 
    values = json_tree.item(selected,'values') 

    logo_lb.insert(0, values[0]) 
    name_lb.insert(0,values[1])
    lastname_lb.insert(0,values[2])
    something_lb.insert(0,values[3])

select_btn = tk.Button(frame2, text="Select", command=select_record)
select_btn.pack(side=LEFT, ipadx=30,)

def update_record():        
    selected = json_tree.focus()
    data = json_tree.item(selected, text='', values=(str(logo_lb.get()),str(name_lb.get()),str(lastname_lb.get()),str(something_lb.get()))) #guardar data
    
    with open('prueba1.json', 'w') as f:
        json.dump({'Example': data}, f, indent=4)
    

    logo_lb.delete(0,END) 
    name_lb.delete(0,END)
    lastname_lb.delete(0,END)
    something_lb.delete(0,END)

update_btn = tk.Button(frame2, text="Update", command=update_record)
update_btn.pack(side=RIGHT,ipadx=30, pady=10)

ventana.mainloop()
{
  "Example": [
    {
      "Logo": "C:/Users/*/Desktop/Tkinter/logos/selavalacarita.png",
      "Name": "2",
      "Last Name": "3",
      "Something": "4"
    },
    {
      "Logo": "C:/Users/*/Desktop/Tkinter/logos/selavalacarita.png",
      "Name": "1",
      "Last Name": "4",
      "Something": "7"
    }
  ]
}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  tkinter - update/refresh treeview snakes 5 20,554 Dec-02-2023, 07:05 PM
Last Post: aynous19
  [Tkinter] Search data in treeview without search button TomasSanchexx 3 1,529 Aug-12-2023, 03:17 AM
Last Post: deanhystad
  TKinter JSON Key Error Nu2Python 4 1,332 Jan-02-2023, 10:15 PM
Last Post: Nu2Python
  [Tkinter] Different rows colours in treeview tkinter Krissstian 1 1,188 Nov-20-2022, 09:59 PM
Last Post: woooee
  [Tkinter] About Tkinter Treeview.selection_get() usage. water 3 8,149 Feb-12-2022, 02:19 PM
Last Post: water
  [Tkinter] [split] Is there a way to embed a treeview as a row inside another treeview? CyKlop 5 3,303 Oct-20-2021, 12:14 AM
Last Post: CyKlop
  [Tkinter] How to insert 'Checkbutton' to 'Treeview' and associate each item? water 2 12,996 Dec-19-2020, 05:24 PM
Last Post: water
  [Tkinter] acceleration of data output in treeview tkinter Vladimir1984 4 4,096 Nov-21-2020, 03:43 PM
Last Post: Vladimir1984
  tkinter| listbox.insert problem Maryan 3 3,438 Sep-29-2020, 05:34 PM
Last Post: Yoriz
  how to insert image into Text widget Tkinter atlass218 5 9,938 Apr-17-2019, 05:28 AM
Last Post: atlass218

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020