简体   繁体   English

读写列表,Python Pickle

[英]Write and Read List, Python Pickle

I made a program with a List and this List is included in the Combobox. 我制作了一个带有列表的程序,该列表包含在组合框中。 I want to write the List into a file in order to read the List again later, even after a restart of the program. 我想将列表写入文件中,以便以后再次读取列表,即使在重新启动程序之后也是如此。

I tried this: 我尝试了这个:

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

You just need to save the list to the file after mainloop, and load it at the start of the program. 您只需要将列表保存到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)

This will load the list at the start, and save it after the tk window closes. 这将在开始时加载列表,并在tk窗口关闭后将其保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM