Почему мои данные не работают с Pickle на Python? - PullRequest
0 голосов
/ 22 сентября 2018

Я в основном делаю приложение tkinter на python, где я могу добавлять записи, а затем сохранять их вручную из предоставленного меню.Прямо сейчас я работаю над сохранением словаря в байты и в файл с помощью модуля Python Pickle.Но когда я использую программирование, необходимо сохранить / .dump словарь в файл и загрузить / .load файл.Есть проблема.

Проблема в том, что файл ничего не загружает и не сохраняет, и я знаю это, потому что я сделал так, чтобы вы могли видеть, что загружено.И я действительно хочу продолжить этот проект и завершить его, поэтому, пожалуйста, могу ли я получить помощь?Вот код:

from tkinter import *
import tkinter as tk
from tkinter import messagebox
import datetime
import pickle

Dictionary = {"Admin":["Test", "Testing App", "027745"]} #No data Because nothing is loaded
print(Dictionary)

BackgroundColor = "#D3D3D3"
Height = 350
Width = 550

window = Tk()
window.title("Record Library | By Ambrose")
window.configure(background=BackgroundColor)
window.minsize(width = Width, height = Height)
window.maxsize(width = Width, height = Height)
#-------------------------------------------
# Variables
#-------------------------------------------

TimeRightNow = str(datetime.datetime.now())
FilteredTime = str("Date : " + TimeRightNow[0] + TimeRightNow[1] + TimeRightNow[2] + TimeRightNow[3] + TimeRightNow[4] + TimeRightNow[5] + TimeRightNow[6] + TimeRightNow[7] + TimeRightNow[8] + TimeRightNow[9] + " | Time : " + TimeRightNow[11] + TimeRightNow[12] + TimeRightNow[13] + TimeRightNow[14] + TimeRightNow[15])

NameTitle_Txt = StringVar()
Information_Txt = StringVar()
Extra_Txt = StringVar()
IDCode_Txt = StringVar()
#-------------------------------------------
# Functions
#-------------------------------------------

def Save():
    print("_Saving... | " + FilteredTime)
    DataFile_ToSave = open("RecordLibrary_Data.p","wb")#Save Data
    pickle.dump(Dictionary, DataFile_ToSave)
    DataFile_ToSave.close()

def Load():
    print("_Loading... | " + FilteredTime)
    DataFile_ToLoad = open("RecordLibrary_Data.p","rb") #Load Data
    Dictionary = pickle.load(DataFile_ToLoad)
    DataFile_ToLoad.close()

def ShowData():
    print("_Loading Data")
    print("_Data loaded : " + str(Dictionary))
def ViewAll_Command():
    print("_Viewing All | " + FilteredTime)

def SearchEntry_Command():
    print("_Searching Entry | " + FilteredTime)

def AddEntry_Command():
    print("_Adding Entry | " + FilteredTime)
    RecordBox.insert(tk.END, "Name/Title : " + NameTitle_Txt.get() + " | Information : " + Information_Txt.get() + " | Extra :" + Extra_Txt.get() + " | Id : " + IDCode_Txt.get())
    Dictionary[str(NameTitle_Txt)] = [str(Information_Txt), str(Extra_Txt), str(IDCode_Txt)]

def UpdateEntry_Command():
    print("_Updating Entry | " + FilteredTime)

def DeleteEntry_Command():
    print("_Deleting Entry | " + FilteredTime)

#-------------------------------------------
# Labels [DONE]
#-------------------------------------------
NameLabel = Label(window, text="Name / Title", background=BackgroundColor)
NameLabel.grid(row=0, column=0)

InformationLabel = Label(window, text="Information", background=BackgroundColor)
InformationLabel.grid(row=0, column=2)

ExtraLabel = Label(window, text="Extra", background=BackgroundColor)
ExtraLabel.grid(row=1, column=0)

IdCodeLabel = Label(window, text="ID / Code", background=BackgroundColor)
IdCodeLabel.grid(row=1, column=2)

#-------------------------------------------
# Entries / Entry Boxes / List
#-------------------------------------------

e1 = Entry(window, textvariable = NameTitle_Txt)
e1.grid(row=0, column=1)

Information_Txt = StringVar()
e2 = Entry(window, textvariable = Information_Txt)
e2.grid(row=0, column=3)

Extra_Txt = StringVar()
e3 = Entry(window, textvariable = Extra_Txt)
e3.grid(row=1, column=1)

IDCode_Txt = StringVar()
e3 = Entry(window, textvariable = IDCode_Txt)
e3.grid(row=1, column=3)

RecordBox = Listbox(window, height=15, width=50)
RecordBox.grid(row=2, column=0, rowspan=6, columnspan=2)

sb1 = Scrollbar(window)
sb1.grid(row=2, column=2, rowspan=6)

sb2 = Scrollbar(window, orient = HORIZONTAL)
sb2.grid(row=9, column=2, rowspan=6)

RecordBox.configure(yscrollcommand=sb1.set, xscrollcommand = sb2.set)
sb1.configure(command=RecordBox.yview)
sb2.configure(command=RecordBox.xview)

#RecordBox.bind('<<ListboxSelect>>', get_selected_row)

#-------------------------------------------
# Buttons [DONE]
#-------------------------------------------
b1 = Button(window, text="View all", width=12, command = ViewAll_Command)
b1.grid(row=2, column=3)

b2 = Button(window, text="Search entry", width=12, command = SearchEntry_Command)
b2.grid(row=3, column=3)

b3 = Button(window, text="Add entry", width=12, command = AddEntry_Command)
b3.grid(row=4, column=3)

b4 = Button(window, text="Update selected", width=12, command = UpdateEntry_Command)
b4.grid(row=5, column=3)

b5 = Button(window, text="Delete selected", width=12, command = DeleteEntry_Command)
b5.grid(row=6, column=3)

b6 = Button(window, text="Close", width=12, command = window.destroy)
b6.grid(row=7, column=3)

#-------------------------------------------
# Menu
#-------------------------------------------
MenuBar = Menu(window)

FileMenu = Menu(MenuBar, tearoff=0)
FileMenu.add_separator()
FileMenu.add_command(label="Load", command = Load)
FileMenu.add_separator()
FileMenu.add_command(label="Save", command = Save)
FileMenu.add_separator()
FileMenu.add_command(label="Show Data", command = ShowData)
MenuBar.add_cascade(label="Data", menu=FileMenu)

#-------------------------------------------
# Last things
#-------------------------------------------

window.config(menu=MenuBar)
window.mainloop()

1 Ответ

0 голосов
/ 22 сентября 2018
def Load():
    print("_Loading... | " + FilteredTime)
    DataFile_ToLoad = open("RecordLibrary_Data.p","rb") #Load Data
    Dictionary = pickle.load(DataFile_ToLoad)
    DataFile_ToLoad.close()

присваивает результат pickle.load новой локальной переменной Dictionary.Вы, вероятно, хотите сохранить его в глобальной переменной:

def Load():
    global Dictionary
    print("_Loading... | " + FilteredTime)
    DataFile_ToLoad = open("RecordLibrary_Data.p","rb") #Load Data
    Dictionary = pickle.load(DataFile_ToLoad)
    DataFile_ToLoad.close()
...