Tkinter 列表框:Botton 从列表框和 JSON 文件中删除所选项目

Tkinter Listbox : Botton delete the selected Items from the Listbox and JSON files

所以我的 Tkinter 菜单上有一个 ListBox,Listbox 上的项目是我的 user.json list-Dict(代码如下)

问题是:如何创建一个按钮,从我的 JSON 列表中删除列表框选择的项目。

我已经知道从列表框中删除项目的代码是:lb.delete(ANCHOR),但我搜索了很多如何从我的 JSON list/dicts 我没有找到任何 result.Thank 你的帮助。

我的列表框:

#LISTBOX

lb = Listbox(tab2, width=40, height=16)
lb.grid(row=0, column=1)
lb.insert(END, "CLIENTS")

for person in data["person"]:
    ans1 = (f"Name: {person['name']}")
    ans2 = (f" City: {person['City']}")
    ans3 = (f" Gender: {person['Gender']}")
    ans = "\n" + ans1 + "\n" + ans2 + "\n" + ans3 + "\n"
    lb.insert(END, ans)

我的功能和按钮

def delt():
    lb.delete(ANCHOR)

Button(tab2, text="DEL", command=delt).grid(row=4, column=1)

我的 JSON 文件

{
  "person": [
    {
      "Name": "Peter",
      "City": "Montreal",
      "Gender": "Male"
    },
    {
      "Name": "Alex",
      "City": "Laval",
      "Gender": "Male"
    },
    {
      "Name": "Annie",
      "City": "Quebec",
      "Gender": "Female"
    }
  ]
}

由于在json文件中,person键是一个字典列表,因此我们的主要任务是将列表框中选择的行转换为字典,然后从中删除该字典person 键并将更改写入 json 文件。

user.json 文件

{
  "person": [
    {
      "Name": "Peter",
      "City": "Montreal",
      "Gender": "Male"
    },
    {
      "Name": "Alex",
      "City": "Laval",
      "Gender": "Male"
    },
    {
      "Name": "Annie",
      "City": "Quebec",
      "Gender": "Female"
    }
  ]
}

代码:

import tkinter as tk
import json

window = tk.Tk()

# selectmode='single' says that you can select only one row at a time in the listbox
lb = tk.Listbox(window, width=40, height=16, selectmode='single')
lb.grid(row=0, column=1)
lb.insert('end', "CLIENTS")

# open and load your user.json file
with open('user.json', 'r') as json_file:
    data = json.load(json_file)

for person in data['person']:
    ans1 = person['Name']
    ans2 = person['City']
    ans3 = person['Gender']
    ans = "\n" + "Name: " + ans1 + " \n" + "City: " + ans2 + " \n" + "Gender: " + ans3 + "\n"
    lb.insert('end', ans)

msg_label = tk.Label(window)
msg_label.grid(row=5, column=1)

def delt():
    with open('user.json', 'r') as json_file:
        data = json.load(json_file)

    # get the values that is under selection in list box
    # it returns one long string in the format you inserted the data in the list box (see above-> ans)
    row_values = lb.get(tk.ACTIVE)

    # split the results into a list of words and replace ':' in 'Name:', 'City:' and 'Gender: ' with ''
    row_values = [row_value.replace(':', '') for row_value in row_values.split()]

    # in each list box row,
    # every even index can be thought as keys of a dictionary
    keys = row_values[0::2]
    # every odd index can be thought as values of a dictionary
    values = row_values[1::2]

    # using the keys and values lists, convert the row data into a dict
    # that matches the format of data in your .json file
    row_selection = dict()
    for key, value in zip(keys, values):
        row_selection[key] = value

    # remove the entry from your user.json file
    # if that entry is found in the file
    if row_selection in data['person']:
        data['person'].remove(row_selection)

        # write changes to file
        with open('user.json', 'w') as json_file:
            data = json.dump(data, json_file)

        # delete the entry from listbox    
        lb.delete(tk.ANCHOR)

        msg_label.config(text='Row removed from file')
    else:
        msg_label.config(text='Row not found in the file')

delete_btn = tk.Button(window, text="DEL", command=delt)
delete_btn.grid(row=4, column=1)


我试图用注释来解释每一行。希望你能理解我的解释。尝试打印 delt() 函数中的每个变量以使其清晰。