写和读列表,Python Pickle
我制作了一个带有列表的程序,这个列表包含在组合框中。我想将列表写入一个文件,以便以后再次读取列表,即使在程序重新启动后也是如此写和读列表,Python Pickle,python,list,tkinter,pickle,Python,List,Tkinter,Pickle,我制作了一个带有列表的程序,这个列表包含在组合框中。我想将列表写入一个文件,以便以后再次读取列表,即使在程序重新启动后也是如此 with open('data.txt', 'rb') as file: data = pickle.load(file) ... win.mainloop() with open('data.txt', 'wb') as file: pickle.dump(data, file) 我试过这个: import tkinter as tk from
with open('data.txt', 'rb') as file:
data = pickle.load(file)
...
win.mainloop()
with open('data.txt', 'wb') as file:
pickle.dump(data, file)
我试过这个:
import tkinter as tk
from tkinter import ttk
import pickle
# window
win = tk.Tk()
win.title("menu")
List = []
newList = []
with open('data.txt', 'wb') as f:
pickle.dump(List, f)
with open('data.txt', 'rb') as f:
newList = pickle.load(f)
# button click event
def clickMe():
List.append(name.get())
numberChosen.configure(values=List)
# text box entry
ttk.Label(win, text="Eingabe:").grid(column=0, row=0)
name = tk.StringVar()
nameEntered = ttk.Entry(win, width=12, textvariable=name)
nameEntered.grid(column=0, row=1)
# button
action = ttk.Button(win, text="Enter", command=clickMe)
action.grid(column=2, row=1)
# drop down menu
ttk.Label(win, text="Auswahl:").grid(column=1, row=0)
number = tk.StringVar()
numberChosen = ttk.Combobox(win, width=12)
numberChosen['values'] = [List]
numberChosen.grid(column=1, row=1)
win.mainloop()
您只需要在mainloop之后将列表保存到文件中,并在程序开始时加载它
with open('data.txt', 'rb') as file:
data = pickle.load(file)
...
win.mainloop()
with open('data.txt', 'wb') as file:
pickle.dump(data, file)
这将在开始时加载列表,并在tk窗口关闭后将其保存。将空列表保存到空文件,然后将其读回的目的是什么?当您在输入框中输入内容时,列表将被填充。是的,但您的代码在开始时将空列表保存到文件,然后重新读取