首页 > 解决方案 > Tkinter Treeview 将数据附加到 JSON

问题描述

我在 tkinter 中有以下 Treeview:

#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)

看起来像这样:

截屏

问题是关闭应用程序时,在树视图中输入的数据没有保存。这就是为什么我想将输入的数据保存在.json

为此,我具有以下功能:

#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")

这样做的问题是它只添加最后一条记录,而不是连续添加。

例如,我添加了接下来的 2 种武器:

截图2

.json看起来像这样:

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

代替:

{
    "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"
        }
    ]
}

标签: pythonjsontkintertreeview

解决方案


我将代码的修改留给保存输入信息的函数:

#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")

我还在打开应用程序时将保存的值插入到树视图中,这样可以看到已经添加的武器。

#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']))

推荐阅读