所以我在Tkinter菜单上有一个ListBox,Listbox上的项目是我的user.json list-Dict(下面的代码)
问题是:如何创建一个按钮,以从JSON列表中删除列表框所选项目。
我已经知道从列表框中删除项目的代码,它是:lb.delete(ANCHOR),但是我搜索了很多方法,如何从我的JSON列表中删除选定的列表框dict,但没有找到任何结果。谢谢您的帮助。
我的列表框:
#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)
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
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)
delete_btn = tk.Button(window, text="DEL", command=delt)
delete_btn.grid(row=4, column=1)
我试图用注释解释每一行。希望你理解我的解释。尝试打印delt()
函数中的每个变量以使其清晰。