如何永久保存Tkinter列表框中修改后的列表项?
实现列表项永久保存的解决方案
当前程序的产品列表仅存储在内存中,程序关闭后修改会丢失。要实现永久保存,需要将列表写入本地文件,程序启动时再从文件读取。以下是修改后的完整代码,采用纯文本文件存储(每行一个产品):
import tkinter as tk from tkinter import ttk, ACTIVE, END window = tk.Tk() window.title("برنامهء مغازه") window.geometry("900x500") window.configure(background = "white") window.resizable(width=False,height=False) tab_parent = ttk.Notebook(window) tab_1 = ttk.Frame(tab_parent) tab_2 = ttk.Frame(tab_parent) tab_parent.add(tab_1,text="خرید قسطی") tab_parent.add(tab_2,text="کالاها") def Update(data): list_box.delete(0,END) for item in data: list_box.insert(END,item) def fillout(e): entry_search.delete(0,END) entry_search.insert(0,list_box.get(ACTIVE)) def check(e): typed = entry_search.get() if typed == "": data = products else: data = [] for item in products: if typed in item: data.append(item) Update(data) # 从文件加载产品列表,文件不存在则返回默认值 def load_products(): try: with open("products.txt", "r", encoding="utf-8") as f: return [line.strip() for line in f if line.strip()] except FileNotFoundError: return ["مخلوط کن دلمونتی", "هم زن حرفه ای دلمونتی ", "غذا ساز 4 کاره دلمونتی", "آب مرکبات گیر دلمونتی"] # 将产品列表保存到文件 def save_products(): with open("products.txt", "w", encoding="utf-8") as f: for item in products: f.write(item + "\n") label_search = tk.Label(tab_2,text="جستجو") label_search.grid(column=0,row=0) label_search.pack() entry_search = tk.Entry(tab_2,justify="right",width="60") entry_search.pack(pady=5) list_box = tk.Listbox(tab_2,justify="right",width="60") list_box.pack(pady=15) # 初始化产品列表,优先从文件加载 products = load_products() def edit(): typed_2 = entry_search.get() if typed_2 == "": data = products elif typed_2 in products: global index_item_in_products index_item_in_products = products.index(typed_2) def confirm(): typed_3 = entry_search.get() products[index_item_in_products] = typed_3 Update(products) save_products() # 修改后立即保存到文件 btn_edit = tk.Button(tab_2,text="ویرایش",command=edit) btn_edit.pack(pady=5) btn_edit_confirm = tk.Button(tab_2,text="تایید ویرایش",command=confirm) btn_edit_confirm.pack(pady=10) Update(products) list_box.bind("<<ListboxSelect>>",fillout) entry_search.bind('<KeyRelease>',check) tab_parent.pack() window.mainloop()
关键修改说明:
load_products()函数:程序启动时读取products.txt文件,解析每行内容作为产品列表;如果文件不存在(首次运行),则使用默认的产品列表。save_products()函数:将当前的产品列表逐行写入products.txt文件,覆盖原有内容,确保修改被永久保存。confirm()函数:在修改产品列表后,调用save_products()将更新后的列表写入文件。- 采用
utf-8编码读写文件,避免波斯语文字出现乱码问题。
内容的提问来源于stack exchange,提问作者Hooman Mirzaei
相关产品推荐
相关产品推荐

