Home > Blockchain >  Tkinter Treeview append data to JSON
Tkinter Treeview append data to JSON

Time:09-17

I have the following Treeview in tkinter:

#Styling the Treeview below
style = ttk.Style()
style.theme_use("alt")
style.configure("Treeview",
    background="silver",
    foreground="green",
    )
style.map('Treeview',
    background=[('selected','#FF1800')])
#Weapons list Treeview
weaponList = ttk.Treeview(root,columns=("Game","Weapon","Down","Up","Left","Right"))
#Setting columns text
weaponList.heading("Game",text="Game")
weaponList.heading("Weapon",text="Weapon")
weaponList.heading("Down",text="Down")
weaponList.heading("Up",text="Up")
weaponList.heading("Left",text="Left")
weaponList.heading("Right",text="Right")

#Show headings (remove extra column)
weaponList['show']='headings'

#Setting columns width and align
weaponList.column("Game",width=60, anchor="center")
weaponList.column("Weapon",width=70, anchor="center")
weaponList.column("Down",width=60, anchor="center")
weaponList.column("Up",width=40, anchor="center")
weaponList.column("Left",width=40, anchor="center")
weaponList.column("Right",width=50, anchor="center")

weaponList.place(x=330,y=120, width=350,height=420)

Which looks like this:

screenshot

The question is that when closing the application, the data entered in the treeview is not saved. That is why I want to save the entered data in a .json

For this I have the following function:

#Add weapon to ListBox when click the AddWeapon Button
def addWeapon():
        if (noAddDefaultWeaponValues()==False):
            tkinter.messagebox.showerror('Weapon add error','You have entered the defaults values or empty data!')
            return
        #Adding data
        data = {}
        data['weapons'] = []
        data['weapons'].append({
            'game': weaponGameEntry.get(),
            'weapon': weaponNameEntry.get(),
            'down': recoilDownEntry.get(),
            'up': recoilUpEntry.get(),
            'left': recoilLeftEntry.get(),
            'right': recoilRightEntry.get()
        })

        with open('json/weapons.json', 'w') as save:
            json.dump(data, save, indent=4)

        weaponList.insert(parent='', index='end', text="", values=(weaponGameEntry.get(), weaponNameEntry.get(),recoilDownEntry.get(),recoilUpEntry.get(),recoilLeftEntry.get(),recoilRightEntry.get()))

        #Clear boxes when add and insert the default values
        weaponGameEntry.delete(0,END)
        weaponGameEntry.insert(0,"INSERT GAME")
        weaponNameEntry.delete(0,END)
        weaponNameEntry.insert(0,"INSERT WEAPON")
        recoilDownEntry.delete(0,END)
        recoilDownEntry.insert(0,"0")
        recoilUpEntry.delete(0,END)
        recoilUpEntry.insert(0,"0")
        recoilLeftEntry.delete(0,END)
        recoilLeftEntry.insert(0,"0")
        recoilRightEntry.delete(0,END)
        recoilRightEntry.insert(0,"0")

The problem with this is that it only adds the last record, instead of adding consecutively.

For example, I add the next 2 weapons:

screenshot2

And the .json looks like this :

{
    "weapons": [
        {
            "game": "GAME2",
            "weapon": "WEAPON2",
            "down": "0",
            "up": "0",
            "left": "0",
            "right": "0"
        }
    ]
}

Instead of:

{
    "weapons": [
        {
            "game": "GAME1",
            "weapon": "WEAPON1",
            "down": "0",
            "up": "0",
            "left": "0",
            "right": "0"
        },
        {
            "game": "GAME2",
            "weapon": "WEAPON2",
            "down": "0",
            "up": "0",
            "left": "0",
            "right": "0"
        }
    ]
}

CodePudding user response:

I leave my modification of the code with the function where the input information is saved :

#Add weapon to ListBox when click the AddWeapon Button
def addWeapon():
        if (noAddDefaultWeaponValues()==False):
            tkinter.messagebox.showerror('Weapon add error','You have entered the defaults values or empty data!')
            return
        #Adding data to json file
        with open('json/weapons.json', 'r') as save:
            weaponsList = json.loads(save.read())['weapons'] 
            weaponsList.append({
                    'game': weaponGameEntry.get(),
                    'weapon': weaponNameEntry.get(),
                    'down': recoilDownEntry.get(),
                    'up': recoilUpEntry.get(),
                    'left': recoilLeftEntry.get(),
                    'right': recoilRightEntry.get()
                    })
            weaponsDict = {}
            weaponsDict['weapons'] = weaponsList
        with open('json/weapons.json', 'w') as write:
                json.dump(weaponsDict, write, indent=4)

        weaponList.insert(parent='', index='end', text="", values=(weaponGameEntry.get(), weaponNameEntry.get(),recoilDownEntry.get(),recoilUpEntry.get(),recoilLeftEntry.get(),recoilRightEntry.get()))

        #Clear boxes when add and insert the default values
        weaponGameEntry.delete(0,END)
        weaponGameEntry.insert(0,"INSERT GAME")
        weaponNameEntry.delete(0,END)
        weaponNameEntry.insert(0,"INSERT WEAPON")
        recoilDownEntry.delete(0,END)
        recoilDownEntry.insert(0,"0")
        recoilUpEntry.delete(0,END)
        recoilUpEntry.insert(0,"0")
        recoilLeftEntry.delete(0,END)
        recoilLeftEntry.insert(0,"0")
        recoilRightEntry.delete(0,END)
        recoilRightEntry.insert(0,"0")

I also leave the insertion of the saved values ​​to the treeview when opening the application, in this way the weapons already added are seen.

#Inserting the already existing weapons to the listbox
def insert():
        with open('json/weapons.json', 'r') as read:
                weaponsList = json.loads(read.read())['weapons']
                weaponsDict = {}
                weaponsDict['weapons'] = weaponsList

        for weapon in weaponsList:
                weaponList.insert(parent='', index='end', text="", values=(weapon['game'],weapon['weapon'],weapon['down'],weapon['up'],weapon['left'],weapon['right']))
  • Related